]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - include/clang/Basic/Module.h
Vendor import of clang trunk r300422:
[FreeBSD/FreeBSD.git] / include / clang / Basic / Module.h
1 //===--- Module.h - Describe a module ---------------------------*- 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 /// \file
11 /// \brief Defines the clang::Module class, which describes a module in the
12 /// source code.
13 ///
14 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_CLANG_BASIC_MODULE_H
16 #define LLVM_CLANG_BASIC_MODULE_H
17
18 #include "clang/Basic/FileManager.h"
19 #include "clang/Basic/SourceLocation.h"
20 #include "llvm/ADT/ArrayRef.h"
21 #include "llvm/ADT/DenseSet.h"
22 #include "llvm/ADT/PointerIntPair.h"
23 #include "llvm/ADT/PointerUnion.h"
24 #include "llvm/ADT/SetVector.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/STLExtras.h"
27 #include "llvm/ADT/StringMap.h"
28 #include "llvm/ADT/StringRef.h"
29 #include <string>
30 #include <utility>
31 #include <vector>
32
33 namespace llvm {
34   class raw_ostream;
35 }
36
37 namespace clang {
38   
39 class LangOptions;
40 class TargetInfo;
41 class IdentifierInfo;
42   
43 /// \brief Describes the name of a module.
44 typedef SmallVector<std::pair<std::string, SourceLocation>, 2> ModuleId;
45
46 /// The signature of a module, which is a hash of the AST content.
47 struct ASTFileSignature : std::array<uint32_t, 5> {
48   ASTFileSignature(std::array<uint32_t, 5> S = {{0}})
49       : std::array<uint32_t, 5>(std::move(S)) {}
50
51   explicit operator bool() const {
52     return *this != std::array<uint32_t, 5>({{0}});
53   }
54 };
55
56 /// \brief Describes a module or submodule.
57 class Module {
58 public:
59   /// \brief The name of this module.
60   std::string Name;
61   
62   /// \brief The location of the module definition.
63   SourceLocation DefinitionLoc;
64
65   /// \brief The parent of this module. This will be NULL for the top-level
66   /// module.
67   Module *Parent;
68
69   /// \brief The build directory of this module. This is the directory in
70   /// which the module is notionally built, and relative to which its headers
71   /// are found.
72   const DirectoryEntry *Directory;
73
74   /// \brief The umbrella header or directory.
75   llvm::PointerUnion<const DirectoryEntry *, const FileEntry *> Umbrella;
76
77   /// \brief The module signature.
78   ASTFileSignature Signature;
79
80   /// \brief The name of the umbrella entry, as written in the module map.
81   std::string UmbrellaAsWritten;
82   
83 private:
84   /// \brief The submodules of this module, indexed by name.
85   std::vector<Module *> SubModules;
86   
87   /// \brief A mapping from the submodule name to the index into the 
88   /// \c SubModules vector at which that submodule resides.
89   llvm::StringMap<unsigned> SubModuleIndex;
90
91   /// \brief The AST file if this is a top-level module which has a
92   /// corresponding serialized AST file, or null otherwise.
93   const FileEntry *ASTFile;
94
95   /// \brief The top-level headers associated with this module.
96   llvm::SmallSetVector<const FileEntry *, 2> TopHeaders;
97
98   /// \brief top-level header filenames that aren't resolved to FileEntries yet.
99   std::vector<std::string> TopHeaderNames;
100
101   /// \brief Cache of modules visible to lookup in this module.
102   mutable llvm::DenseSet<const Module*> VisibleModulesCache;
103
104   /// The ID used when referencing this module within a VisibleModuleSet.
105   unsigned VisibilityID;
106
107 public:
108   enum HeaderKind {
109     HK_Normal,
110     HK_Textual,
111     HK_Private,
112     HK_PrivateTextual,
113     HK_Excluded
114   };
115   static const int NumHeaderKinds = HK_Excluded + 1;
116
117   /// \brief Information about a header directive as found in the module map
118   /// file.
119   struct Header {
120     std::string NameAsWritten;
121     const FileEntry *Entry;
122
123     explicit operator bool() { return Entry; }
124   };
125
126   /// \brief Information about a directory name as found in the module map
127   /// file.
128   struct DirectoryName {
129     std::string NameAsWritten;
130     const DirectoryEntry *Entry;
131
132     explicit operator bool() { return Entry; }
133   };
134
135   /// \brief The headers that are part of this module.
136   SmallVector<Header, 2> Headers[5];
137
138   /// \brief Stored information about a header directive that was found in the
139   /// module map file but has not been resolved to a file.
140   struct UnresolvedHeaderDirective {
141     SourceLocation FileNameLoc;
142     std::string FileName;
143     bool IsUmbrella;
144   };
145
146   /// \brief Headers that are mentioned in the module map file but could not be
147   /// found on the file system.
148   SmallVector<UnresolvedHeaderDirective, 1> MissingHeaders;
149
150   /// \brief An individual requirement: a feature name and a flag indicating
151   /// the required state of that feature.
152   typedef std::pair<std::string, bool> Requirement;
153
154   /// \brief The set of language features required to use this module.
155   ///
156   /// If any of these requirements are not available, the \c IsAvailable bit
157   /// will be false to indicate that this (sub)module is not available.
158   SmallVector<Requirement, 2> Requirements;
159
160   /// \brief Whether this module is missing a feature from \c Requirements.
161   unsigned IsMissingRequirement : 1;
162
163   /// \brief Whether we tried and failed to load a module file for this module.
164   unsigned HasIncompatibleModuleFile : 1;
165
166   /// \brief Whether this module is available in the current translation unit.
167   ///
168   /// If the module is missing headers or does not meet all requirements then
169   /// this bit will be 0.
170   unsigned IsAvailable : 1;
171
172   /// \brief Whether this module was loaded from a module file.
173   unsigned IsFromModuleFile : 1;
174   
175   /// \brief Whether this is a framework module.
176   unsigned IsFramework : 1;
177   
178   /// \brief Whether this is an explicit submodule.
179   unsigned IsExplicit : 1;
180   
181   /// \brief Whether this is a "system" module (which assumes that all
182   /// headers in it are system headers).
183   unsigned IsSystem : 1;
184
185   /// \brief Whether this is an 'extern "C"' module (which implicitly puts all
186   /// headers in it within an 'extern "C"' block, and allows the module to be
187   /// imported within such a block).
188   unsigned IsExternC : 1;
189
190   /// \brief Whether this is an inferred submodule (module * { ... }).
191   unsigned IsInferred : 1;
192
193   /// \brief Whether we should infer submodules for this module based on 
194   /// the headers.
195   ///
196   /// Submodules can only be inferred for modules with an umbrella header.
197   unsigned InferSubmodules : 1;
198   
199   /// \brief Whether, when inferring submodules, the inferred submodules
200   /// should be explicit.
201   unsigned InferExplicitSubmodules : 1;
202   
203   /// \brief Whether, when inferring submodules, the inferr submodules should
204   /// export all modules they import (e.g., the equivalent of "export *").
205   unsigned InferExportWildcard : 1;
206
207   /// \brief Whether the set of configuration macros is exhaustive.
208   ///
209   /// When the set of configuration macros is exhaustive, meaning
210   /// that no identifier not in this list should affect how the module is
211   /// built.
212   unsigned ConfigMacrosExhaustive : 1;
213
214   /// \brief Whether files in this module can only include non-modular headers
215   /// and headers from used modules.
216   unsigned NoUndeclaredIncludes : 1;
217
218   /// \brief Describes the visibility of the various names within a
219   /// particular module.
220   enum NameVisibilityKind {
221     /// \brief All of the names in this module are hidden.
222     Hidden,
223     /// \brief All of the names in this module are visible.
224     AllVisible
225   };
226
227   /// \brief The visibility of names within this particular module.
228   NameVisibilityKind NameVisibility;
229
230   /// \brief The location of the inferred submodule.
231   SourceLocation InferredSubmoduleLoc;
232
233   /// \brief The set of modules imported by this module, and on which this
234   /// module depends.
235   llvm::SmallSetVector<Module *, 2> Imports;
236   
237   /// \brief Describes an exported module.
238   ///
239   /// The pointer is the module being re-exported, while the bit will be true
240   /// to indicate that this is a wildcard export.
241   typedef llvm::PointerIntPair<Module *, 1, bool> ExportDecl;
242   
243   /// \brief The set of export declarations.
244   SmallVector<ExportDecl, 2> Exports;
245   
246   /// \brief Describes an exported module that has not yet been resolved
247   /// (perhaps because the module it refers to has not yet been loaded).
248   struct UnresolvedExportDecl {
249     /// \brief The location of the 'export' keyword in the module map file.
250     SourceLocation ExportLoc;
251     
252     /// \brief The name of the module.
253     ModuleId Id;
254     
255     /// \brief Whether this export declaration ends in a wildcard, indicating
256     /// that all of its submodules should be exported (rather than the named
257     /// module itself).
258     bool Wildcard;
259   };
260   
261   /// \brief The set of export declarations that have yet to be resolved.
262   SmallVector<UnresolvedExportDecl, 2> UnresolvedExports;
263
264   /// \brief The directly used modules.
265   SmallVector<Module *, 2> DirectUses;
266
267   /// \brief The set of use declarations that have yet to be resolved.
268   SmallVector<ModuleId, 2> UnresolvedDirectUses;
269
270   /// \brief A library or framework to link against when an entity from this
271   /// module is used.
272   struct LinkLibrary {
273     LinkLibrary() : IsFramework(false) { }
274     LinkLibrary(const std::string &Library, bool IsFramework)
275       : Library(Library), IsFramework(IsFramework) { }
276     
277     /// \brief The library to link against.
278     ///
279     /// This will typically be a library or framework name, but can also
280     /// be an absolute path to the library or framework.
281     std::string Library;
282
283     /// \brief Whether this is a framework rather than a library.
284     bool IsFramework;
285   };
286
287   /// \brief The set of libraries or frameworks to link against when
288   /// an entity from this module is used.
289   llvm::SmallVector<LinkLibrary, 2> LinkLibraries;
290
291   /// \brief The set of "configuration macros", which are macros that
292   /// (intentionally) change how this module is built.
293   std::vector<std::string> ConfigMacros;
294
295   /// \brief An unresolved conflict with another module.
296   struct UnresolvedConflict {
297     /// \brief The (unresolved) module id.
298     ModuleId Id;
299
300     /// \brief The message provided to the user when there is a conflict.
301     std::string Message;
302   };
303
304   /// \brief The list of conflicts for which the module-id has not yet been
305   /// resolved.
306   std::vector<UnresolvedConflict> UnresolvedConflicts;
307
308   /// \brief A conflict between two modules.
309   struct Conflict {
310     /// \brief The module that this module conflicts with.
311     Module *Other;
312
313     /// \brief The message provided to the user when there is a conflict.
314     std::string Message;
315   };
316
317   /// \brief The list of conflicts.
318   std::vector<Conflict> Conflicts;
319
320   /// \brief Construct a new module or submodule.
321   Module(StringRef Name, SourceLocation DefinitionLoc, Module *Parent,
322          bool IsFramework, bool IsExplicit, unsigned VisibilityID);
323   
324   ~Module();
325   
326   /// \brief Determine whether this module is available for use within the
327   /// current translation unit.
328   bool isAvailable() const { return IsAvailable; }
329
330   /// \brief Determine whether this module is available for use within the
331   /// current translation unit.
332   ///
333   /// \param LangOpts The language options used for the current
334   /// translation unit.
335   ///
336   /// \param Target The target options used for the current translation unit.
337   ///
338   /// \param Req If this module is unavailable, this parameter
339   /// will be set to one of the requirements that is not met for use of
340   /// this module.
341   bool isAvailable(const LangOptions &LangOpts, 
342                    const TargetInfo &Target,
343                    Requirement &Req,
344                    UnresolvedHeaderDirective &MissingHeader) const;
345
346   /// \brief Determine whether this module is a submodule.
347   bool isSubModule() const { return Parent != nullptr; }
348   
349   /// \brief Determine whether this module is a submodule of the given other
350   /// module.
351   bool isSubModuleOf(const Module *Other) const;
352   
353   /// \brief Determine whether this module is a part of a framework,
354   /// either because it is a framework module or because it is a submodule
355   /// of a framework module.
356   bool isPartOfFramework() const {
357     for (const Module *Mod = this; Mod; Mod = Mod->Parent) 
358       if (Mod->IsFramework)
359         return true;
360     
361     return false;
362   }
363
364   /// \brief Determine whether this module is a subframework of another
365   /// framework.
366   bool isSubFramework() const {
367     return IsFramework && Parent && Parent->isPartOfFramework();
368   }
369
370   /// \brief Retrieve the full name of this module, including the path from
371   /// its top-level module.
372   std::string getFullModuleName() const;
373
374   /// \brief Whether the full name of this module is equal to joining
375   /// \p nameParts with "."s.
376   ///
377   /// This is more efficient than getFullModuleName().
378   bool fullModuleNameIs(ArrayRef<StringRef> nameParts) const;
379
380   /// \brief Retrieve the top-level module for this (sub)module, which may
381   /// be this module.
382   Module *getTopLevelModule() {
383     return const_cast<Module *>(
384              const_cast<const Module *>(this)->getTopLevelModule());
385   }
386
387   /// \brief Retrieve the top-level module for this (sub)module, which may
388   /// be this module.
389   const Module *getTopLevelModule() const;
390   
391   /// \brief Retrieve the name of the top-level module.
392   ///
393   StringRef getTopLevelModuleName() const {
394     return getTopLevelModule()->Name;
395   }
396
397   /// \brief The serialized AST file for this module, if one was created.
398   const FileEntry *getASTFile() const {
399     return getTopLevelModule()->ASTFile;
400   }
401
402   /// \brief Set the serialized AST file for the top-level module of this module.
403   void setASTFile(const FileEntry *File) {
404     assert((File == nullptr || getASTFile() == nullptr ||
405             getASTFile() == File) && "file path changed");
406     getTopLevelModule()->ASTFile = File;
407   }
408
409   /// \brief Retrieve the directory for which this module serves as the
410   /// umbrella.
411   DirectoryName getUmbrellaDir() const;
412
413   /// \brief Retrieve the header that serves as the umbrella header for this
414   /// module.
415   Header getUmbrellaHeader() const {
416     if (auto *E = Umbrella.dyn_cast<const FileEntry *>())
417       return Header{UmbrellaAsWritten, E};
418     return Header{};
419   }
420
421   /// \brief Determine whether this module has an umbrella directory that is
422   /// not based on an umbrella header.
423   bool hasUmbrellaDir() const {
424     return Umbrella && Umbrella.is<const DirectoryEntry *>();
425   }
426
427   /// \brief Add a top-level header associated with this module.
428   void addTopHeader(const FileEntry *File) {
429     assert(File);
430     TopHeaders.insert(File);
431   }
432
433   /// \brief Add a top-level header filename associated with this module.
434   void addTopHeaderFilename(StringRef Filename) {
435     TopHeaderNames.push_back(Filename);
436   }
437
438   /// \brief The top-level headers associated with this module.
439   ArrayRef<const FileEntry *> getTopHeaders(FileManager &FileMgr);
440
441   /// \brief Determine whether this module has declared its intention to
442   /// directly use another module.
443   bool directlyUses(const Module *Requested) const;
444
445   /// \brief Add the given feature requirement to the list of features
446   /// required by this module.
447   ///
448   /// \param Feature The feature that is required by this module (and
449   /// its submodules).
450   ///
451   /// \param RequiredState The required state of this feature: \c true
452   /// if it must be present, \c false if it must be absent.
453   ///
454   /// \param LangOpts The set of language options that will be used to
455   /// evaluate the availability of this feature.
456   ///
457   /// \param Target The target options that will be used to evaluate the
458   /// availability of this feature.
459   void addRequirement(StringRef Feature, bool RequiredState,
460                       const LangOptions &LangOpts,
461                       const TargetInfo &Target);
462
463   /// \brief Mark this module and all of its submodules as unavailable.
464   void markUnavailable(bool MissingRequirement = false);
465
466   /// \brief Find the submodule with the given name.
467   ///
468   /// \returns The submodule if found, or NULL otherwise.
469   Module *findSubmodule(StringRef Name) const;
470
471   /// \brief Determine whether the specified module would be visible to
472   /// a lookup at the end of this module.
473   ///
474   /// FIXME: This may return incorrect results for (submodules of) the
475   /// module currently being built, if it's queried before we see all
476   /// of its imports.
477   bool isModuleVisible(const Module *M) const {
478     if (VisibleModulesCache.empty())
479       buildVisibleModulesCache();
480     return VisibleModulesCache.count(M);
481   }
482
483   unsigned getVisibilityID() const { return VisibilityID; }
484
485   typedef std::vector<Module *>::iterator submodule_iterator;
486   typedef std::vector<Module *>::const_iterator submodule_const_iterator;
487   
488   submodule_iterator submodule_begin() { return SubModules.begin(); }
489   submodule_const_iterator submodule_begin() const {return SubModules.begin();}
490   submodule_iterator submodule_end()   { return SubModules.end(); }
491   submodule_const_iterator submodule_end() const { return SubModules.end(); }
492
493   llvm::iterator_range<submodule_iterator> submodules() {
494     return llvm::make_range(submodule_begin(), submodule_end());
495   }
496   llvm::iterator_range<submodule_const_iterator> submodules() const {
497     return llvm::make_range(submodule_begin(), submodule_end());
498   }
499
500   /// \brief Appends this module's list of exported modules to \p Exported.
501   ///
502   /// This provides a subset of immediately imported modules (the ones that are
503   /// directly exported), not the complete set of exported modules.
504   void getExportedModules(SmallVectorImpl<Module *> &Exported) const;
505
506   static StringRef getModuleInputBufferName() {
507     return "<module-includes>";
508   }
509
510   /// \brief Print the module map for this module to the given stream. 
511   ///
512   void print(raw_ostream &OS, unsigned Indent = 0) const;
513   
514   /// \brief Dump the contents of this module to the given output stream.
515   void dump() const;
516
517 private:
518   void buildVisibleModulesCache() const;
519 };
520
521 /// \brief A set of visible modules.
522 class VisibleModuleSet {
523 public:
524   VisibleModuleSet() : Generation(0) {}
525   VisibleModuleSet(VisibleModuleSet &&O)
526       : ImportLocs(std::move(O.ImportLocs)), Generation(O.Generation ? 1 : 0) {
527     O.ImportLocs.clear();
528     ++O.Generation;
529   }
530
531   /// Move from another visible modules set. Guaranteed to leave the source
532   /// empty and bump the generation on both.
533   VisibleModuleSet &operator=(VisibleModuleSet &&O) {
534     ImportLocs = std::move(O.ImportLocs);
535     O.ImportLocs.clear();
536     ++O.Generation;
537     ++Generation;
538     return *this;
539   }
540
541   /// \brief Get the current visibility generation. Incremented each time the
542   /// set of visible modules changes in any way.
543   unsigned getGeneration() const { return Generation; }
544
545   /// \brief Determine whether a module is visible.
546   bool isVisible(const Module *M) const {
547     return getImportLoc(M).isValid();
548   }
549
550   /// \brief Get the location at which the import of a module was triggered.
551   SourceLocation getImportLoc(const Module *M) const {
552     return M->getVisibilityID() < ImportLocs.size()
553                ? ImportLocs[M->getVisibilityID()]
554                : SourceLocation();
555   }
556
557   /// \brief A callback to call when a module is made visible (directly or
558   /// indirectly) by a call to \ref setVisible.
559   typedef llvm::function_ref<void(Module *M)> VisibleCallback;
560   /// \brief A callback to call when a module conflict is found. \p Path
561   /// consists of a sequence of modules from the conflicting module to the one
562   /// made visible, where each was exported by the next.
563   typedef llvm::function_ref<void(ArrayRef<Module *> Path,
564                                   Module *Conflict, StringRef Message)>
565       ConflictCallback;
566   /// \brief Make a specific module visible.
567   void setVisible(Module *M, SourceLocation Loc,
568                   VisibleCallback Vis = [](Module *) {},
569                   ConflictCallback Cb = [](ArrayRef<Module *>, Module *,
570                                            StringRef) {});
571
572 private:
573   /// Import locations for each visible module. Indexed by the module's
574   /// VisibilityID.
575   std::vector<SourceLocation> ImportLocs;
576   /// Visibility generation, bumped every time the visibility state changes.
577   unsigned Generation;
578 };
579
580 } // end namespace clang
581
582
583 #endif // LLVM_CLANG_BASIC_MODULE_H