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