Clang Project

clang_source_code/include/clang/Lex/HeaderSearch.h
1//===- HeaderSearch.h - Resolve Header File Locations -----------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the HeaderSearch interface.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_LEX_HEADERSEARCH_H
14#define LLVM_CLANG_LEX_HEADERSEARCH_H
15
16#include "clang/Basic/SourceLocation.h"
17#include "clang/Basic/SourceManager.h"
18#include "clang/Lex/DirectoryLookup.h"
19#include "clang/Lex/HeaderMap.h"
20#include "clang/Lex/ModuleMap.h"
21#include "llvm/ADT/ArrayRef.h"
22#include "llvm/ADT/DenseMap.h"
23#include "llvm/ADT/StringMap.h"
24#include "llvm/ADT/StringSet.h"
25#include "llvm/ADT/StringRef.h"
26#include "llvm/Support/Allocator.h"
27#include <cassert>
28#include <cstddef>
29#include <memory>
30#include <string>
31#include <utility>
32#include <vector>
33
34namespace clang {
35
36class DiagnosticsEngine;
37class DirectoryEntry;
38class ExternalPreprocessorSource;
39class FileEntry;
40class FileManager;
41class HeaderSearchOptions;
42class IdentifierInfo;
43class LangOptions;
44class Module;
45class Preprocessor;
46class TargetInfo;
47
48/// The preprocessor keeps track of this information for each
49/// file that is \#included.
50struct HeaderFileInfo {
51  /// True if this is a \#import'd or \#pragma once file.
52  unsigned isImport : 1;
53
54  /// True if this is a \#pragma once file.
55  unsigned isPragmaOnce : 1;
56
57  /// Keep track of whether this is a system header, and if so,
58  /// whether it is C++ clean or not.  This can be set by the include paths or
59  /// by \#pragma gcc system_header.  This is an instance of
60  /// SrcMgr::CharacteristicKind.
61  unsigned DirInfo : 3;
62
63  /// Whether this header file info was supplied by an external source,
64  /// and has not changed since.
65  unsigned External : 1;
66
67  /// Whether this header is part of a module.
68  unsigned isModuleHeader : 1;
69
70  /// Whether this header is part of the module that we are building.
71  unsigned isCompilingModuleHeader : 1;
72
73  /// Whether this structure is considered to already have been
74  /// "resolved", meaning that it was loaded from the external source.
75  unsigned Resolved : 1;
76
77  /// Whether this is a header inside a framework that is currently
78  /// being built.
79  ///
80  /// When a framework is being built, the headers have not yet been placed
81  /// into the appropriate framework subdirectories, and therefore are
82  /// provided via a header map. This bit indicates when this is one of
83  /// those framework headers.
84  unsigned IndexHeaderMapHeader : 1;
85
86  /// Whether this file has been looked up as a header.
87  unsigned IsValid : 1;
88
89  /// The number of times the file has been included already.
90  unsigned short NumIncludes = 0;
91
92  /// The ID number of the controlling macro.
93  ///
94  /// This ID number will be non-zero when there is a controlling
95  /// macro whose IdentifierInfo may not yet have been loaded from
96  /// external storage.
97  unsigned ControllingMacroID = 0;
98
99  /// If this file has a \#ifndef XXX (or equivalent) guard that
100  /// protects the entire contents of the file, this is the identifier
101  /// for the macro that controls whether or not it has any effect.
102  ///
103  /// Note: Most clients should use getControllingMacro() to access
104  /// the controlling macro of this header, since
105  /// getControllingMacro() is able to load a controlling macro from
106  /// external storage.
107  const IdentifierInfo *ControllingMacro = nullptr;
108
109  /// If this header came from a framework include, this is the name
110  /// of the framework.
111  StringRef Framework;
112
113  HeaderFileInfo()
114      : isImport(false), isPragmaOnce(false), DirInfo(SrcMgr::C_User),
115        External(false), isModuleHeader(false), isCompilingModuleHeader(false),
116        Resolved(false), IndexHeaderMapHeader(false), IsValid(false)  {}
117
118  /// Retrieve the controlling macro for this header file, if
119  /// any.
120  const IdentifierInfo *
121  getControllingMacro(ExternalPreprocessorSource *External);
122
123  /// Determine whether this is a non-default header file info, e.g.,
124  /// it corresponds to an actual header we've included or tried to include.
125  bool isNonDefault() const {
126    return isImport || isPragmaOnce || NumIncludes || ControllingMacro ||
127      ControllingMacroID;
128  }
129};
130
131/// An external source of header file information, which may supply
132/// information about header files already included.
133class ExternalHeaderFileInfoSource {
134public:
135  virtual ~ExternalHeaderFileInfoSource();
136
137  /// Retrieve the header file information for the given file entry.
138  ///
139  /// \returns Header file information for the given file entry, with the
140  /// \c External bit set. If the file entry is not known, return a
141  /// default-constructed \c HeaderFileInfo.
142  virtual HeaderFileInfo GetHeaderFileInfo(const FileEntry *FE) = 0;
143};
144
145/// This structure is used to record entries in our framework cache.
146struct FrameworkCacheEntry {
147  /// The directory entry which should be used for the cached framework.
148  const DirectoryEntry *Directory;
149
150  /// Whether this framework has been "user-specified" to be treated as if it
151  /// were a system framework (even if it was found outside a system framework
152  /// directory).
153  bool IsUserSpecifiedSystemFramework;
154};
155
156/// Encapsulates the information needed to find the file referenced
157/// by a \#include or \#include_next, (sub-)framework lookup, etc.
158class HeaderSearch {
159  friend class DirectoryLookup;
160
161  /// Header-search options used to initialize this header search.
162  std::shared_ptr<HeaderSearchOptionsHSOpts;
163
164  DiagnosticsEngine &Diags;
165  FileManager &FileMgr;
166
167  /// \#include search path information.  Requests for \#include "x" search the
168  /// directory of the \#including file first, then each directory in SearchDirs
169  /// consecutively. Requests for <x> search the current dir first, then each
170  /// directory in SearchDirs, starting at AngledDirIdx, consecutively.  If
171  /// NoCurDirSearch is true, then the check for the file in the current
172  /// directory is suppressed.
173  std::vector<DirectoryLookupSearchDirs;
174  unsigned AngledDirIdx = 0;
175  unsigned SystemDirIdx = 0;
176  bool NoCurDirSearch = false;
177
178  /// \#include prefixes for which the 'system header' property is
179  /// overridden.
180  ///
181  /// For a \#include "x" or \#include \<x> directive, the last string in this
182  /// list which is a prefix of 'x' determines whether the file is treated as
183  /// a system header.
184  std::vector<std::pair<std::stringbool>> SystemHeaderPrefixes;
185
186  /// The path to the module cache.
187  std::string ModuleCachePath;
188
189  /// All of the preprocessor-specific data about files that are
190  /// included, indexed by the FileEntry's UID.
191  mutable std::vector<HeaderFileInfoFileInfo;
192
193  /// Keeps track of each lookup performed by LookupFile.
194  struct LookupFileCacheInfo {
195    /// Starting index in SearchDirs that the cached search was performed from.
196    /// If there is a hit and this value doesn't match the current query, the
197    /// cache has to be ignored.
198    unsigned StartIdx = 0;
199
200    /// The entry in SearchDirs that satisfied the query.
201    unsigned HitIdx = 0;
202
203    /// This is non-null if the original filename was mapped to a framework
204    /// include via a headermap.
205    const char *MappedName = nullptr;
206
207    /// Default constructor -- Initialize all members with zero.
208    LookupFileCacheInfo() = default;
209
210    void reset(unsigned StartIdx) {
211      this->StartIdx = StartIdx;
212      this->MappedName = nullptr;
213    }
214  };
215  llvm::StringMap<LookupFileCacheInfo, llvm::BumpPtrAllocator> LookupFileCache;
216
217  /// Collection mapping a framework or subframework
218  /// name like "Carbon" to the Carbon.framework directory.
219  llvm::StringMap<FrameworkCacheEntry, llvm::BumpPtrAllocator> FrameworkMap;
220
221  /// Maps include file names (including the quotes or
222  /// angle brackets) to other include file names.  This is used to support the
223  /// include_alias pragma for Microsoft compatibility.
224  using IncludeAliasMap =
225      llvm::StringMap<std::string, llvm::BumpPtrAllocator>;
226  std::unique_ptr<IncludeAliasMap> IncludeAliases;
227
228  /// This is a mapping from FileEntry -> HeaderMap, uniquing headermaps.
229  std::vector<std::pair<const FileEntry *, std::unique_ptr<HeaderMap>>> HeaderMaps;
230
231  /// The mapping between modules and headers.
232  mutable ModuleMap ModMap;
233
234  /// Describes whether a given directory has a module map in it.
235  llvm::DenseMap<const DirectoryEntry *, boolDirectoryHasModuleMap;
236
237  /// Set of module map files we've already loaded, and a flag indicating
238  /// whether they were valid or not.
239  llvm::DenseMap<const FileEntry *, boolLoadedModuleMaps;
240
241  /// Uniqued set of framework names, which is used to track which
242  /// headers were included as framework headers.
243  llvm::StringSet<llvm::BumpPtrAllocator> FrameworkNames;
244
245  /// Entity used to resolve the identifier IDs of controlling
246  /// macros into IdentifierInfo pointers, and keep the identifire up to date,
247  /// as needed.
248  ExternalPreprocessorSource *ExternalLookup = nullptr;
249
250  /// Entity used to look up stored header file information.
251  ExternalHeaderFileInfoSource *ExternalSource = nullptr;
252
253  // Various statistics we track for performance analysis.
254  unsigned NumIncluded = 0;
255  unsigned NumMultiIncludeFileOptzn = 0;
256  unsigned NumFrameworkLookups = 0;
257  unsigned NumSubFrameworkLookups = 0;
258
259public:
260  HeaderSearch(std::shared_ptr<HeaderSearchOptionsHSOpts,
261               SourceManager &SourceMgrDiagnosticsEngine &Diags,
262               const LangOptions &LangOptsconst TargetInfo *Target);
263  HeaderSearch(const HeaderSearch &) = delete;
264  HeaderSearch &operator=(const HeaderSearch &) = delete;
265
266  /// Retrieve the header-search options with which this header search
267  /// was initialized.
268  HeaderSearchOptions &getHeaderSearchOpts() const { return *HSOpts; }
269
270  FileManager &getFileMgr() const { return FileMgr; }
271
272  DiagnosticsEngine &getDiags() const { return Diags; }
273
274  /// Interface for setting the file search paths.
275  void SetSearchPaths(const std::vector<DirectoryLookup> &dirs,
276                      unsigned angledDirIdxunsigned systemDirIdx,
277                      bool noCurDirSearch) {
278     (0) . __assert_fail ("angledDirIdx <= systemDirIdx && systemDirIdx <= dirs.size() && \"Directory indices are unordered\"", "/home/seafit/code_projects/clang_source/clang/include/clang/Lex/HeaderSearch.h", 279, __PRETTY_FUNCTION__))" file_link="../../../../include/assert.h.html#88" macro="true">assert(angledDirIdx <= systemDirIdx && systemDirIdx <= dirs.size() &&
279 (0) . __assert_fail ("angledDirIdx <= systemDirIdx && systemDirIdx <= dirs.size() && \"Directory indices are unordered\"", "/home/seafit/code_projects/clang_source/clang/include/clang/Lex/HeaderSearch.h", 279, __PRETTY_FUNCTION__))" file_link="../../../../include/assert.h.html#88" macro="true">        "Directory indices are unordered");
280    SearchDirs = dirs;
281    AngledDirIdx = angledDirIdx;
282    SystemDirIdx = systemDirIdx;
283    NoCurDirSearch = noCurDirSearch;
284    //LookupFileCache.clear();
285  }
286
287  /// Add an additional search path.
288  void AddSearchPath(const DirectoryLookup &dirbool isAngled) {
289    unsigned idx = isAngled ? SystemDirIdx : AngledDirIdx;
290    SearchDirs.insert(SearchDirs.begin() + idxdir);
291    if (!isAngled)
292      AngledDirIdx++;
293    SystemDirIdx++;
294  }
295
296  /// Set the list of system header prefixes.
297  void SetSystemHeaderPrefixes(ArrayRef<std::pair<std::stringbool>> P) {
298    SystemHeaderPrefixes.assign(P.begin(), P.end());
299  }
300
301  /// Checks whether the map exists or not.
302  bool HasIncludeAliasMap() const { return (bool)IncludeAliases; }
303
304  /// Map the source include name to the dest include name.
305  ///
306  /// The Source should include the angle brackets or quotes, the dest
307  /// should not.  This allows for distinction between <> and "" headers.
308  void AddIncludeAlias(StringRef SourceStringRef Dest) {
309    if (!IncludeAliases)
310      IncludeAliases.reset(new IncludeAliasMap);
311    (*IncludeAliases)[Source] = Dest;
312  }
313
314  /// Maps one header file name to a different header
315  /// file name, for use with the include_alias pragma.  Note that the source
316  /// file name should include the angle brackets or quotes.  Returns StringRef
317  /// as null if the header cannot be mapped.
318  StringRef MapHeaderToIncludeAlias(StringRef Source) {
319     (0) . __assert_fail ("IncludeAliases && \"Trying to map headers when there's no map\"", "/home/seafit/code_projects/clang_source/clang/include/clang/Lex/HeaderSearch.h", 319, __PRETTY_FUNCTION__))" file_link="../../../../include/assert.h.html#88" macro="true">assert(IncludeAliases && "Trying to map headers when there's no map");
320
321    // Do any filename replacements before anything else
322    IncludeAliasMap::const_iterator Iter = IncludeAliases->find(Source);
323    if (Iter != IncludeAliases->end())
324      return Iter->second;
325    return {};
326  }
327
328  /// Set the path to the module cache.
329  void setModuleCachePath(StringRef CachePath) {
330    ModuleCachePath = CachePath;
331  }
332
333  /// Retrieve the path to the module cache.
334  StringRef getModuleCachePath() const { return ModuleCachePath; }
335
336  /// Consider modules when including files from this directory.
337  void setDirectoryHasModuleMap(const DirectoryEntryDir) {
338    DirectoryHasModuleMap[Dir] = true;
339  }
340
341  /// Forget everything we know about headers so far.
342  void ClearFileInfo() {
343    FileInfo.clear();
344  }
345
346  void SetExternalLookup(ExternalPreprocessorSource *EPS) {
347    ExternalLookup = EPS;
348  }
349
350  ExternalPreprocessorSource *getExternalLookup() const {
351    return ExternalLookup;
352  }
353
354  /// Set the external source of header information.
355  void SetExternalSource(ExternalHeaderFileInfoSource *ES) {
356    ExternalSource = ES;
357  }
358
359  /// Set the target information for the header search, if not
360  /// already known.
361  void setTarget(const TargetInfo &Target);
362
363  /// Given a "foo" or \<foo> reference, look up the indicated file,
364  /// return null on failure.
365  ///
366  /// \returns If successful, this returns 'UsedDir', the DirectoryLookup member
367  /// the file was found in, or null if not applicable.
368  ///
369  /// \param IncludeLoc Used for diagnostics if valid.
370  ///
371  /// \param isAngled indicates whether the file reference is a <> reference.
372  ///
373  /// \param CurDir If non-null, the file was found in the specified directory
374  /// search location.  This is used to implement \#include_next.
375  ///
376  /// \param Includers Indicates where the \#including file(s) are, in case
377  /// relative searches are needed. In reverse order of inclusion.
378  ///
379  /// \param SearchPath If non-null, will be set to the search path relative
380  /// to which the file was found. If the include path is absolute, SearchPath
381  /// will be set to an empty string.
382  ///
383  /// \param RelativePath If non-null, will be set to the path relative to
384  /// SearchPath at which the file was found. This only differs from the
385  /// Filename for framework includes.
386  ///
387  /// \param SuggestedModule If non-null, and the file found is semantically
388  /// part of a known module, this will be set to the module that should
389  /// be imported instead of preprocessing/parsing the file found.
390  ///
391  /// \param IsMapped If non-null, and the search involved header maps, set to
392  /// true.
393  ///
394  /// \param IsFrameworkFound If non-null, will be set to true if a framework is
395  /// found in any of searched SearchDirs. Doesn't guarantee the requested file
396  /// is found.
397  const FileEntry *LookupFile(
398      StringRef FilenameSourceLocation IncludeLocbool isAngled,
399      const DirectoryLookup *FromDirconst DirectoryLookup *&CurDir,
400      ArrayRef<std::pair<const FileEntry *, const DirectoryEntry *>> Includers,
401      SmallVectorImpl<char> *SearchPathSmallVectorImpl<char> *RelativePath,
402      Module *RequestingModuleModuleMap::KnownHeader *SuggestedModule,
403      bool *IsMappedbool *IsFrameworkFoundbool SkipCache = false,
404      bool BuildSystemModule = false);
405
406  /// Look up a subframework for the specified \#include file.
407  ///
408  /// For example, if \#include'ing <HIToolbox/HIToolbox.h> from
409  /// within ".../Carbon.framework/Headers/Carbon.h", check to see if
410  /// HIToolbox is a subframework within Carbon.framework.  If so, return
411  /// the FileEntry for the designated file, otherwise return null.
412  const FileEntry *LookupSubframeworkHeader(
413      StringRef Filenameconst FileEntry *ContextFileEnt,
414      SmallVectorImpl<char> *SearchPathSmallVectorImpl<char> *RelativePath,
415      Module *RequestingModuleModuleMap::KnownHeader *SuggestedModule);
416
417  /// Look up the specified framework name in our framework cache.
418  /// \returns The DirectoryEntry it is in if we know, null otherwise.
419  FrameworkCacheEntry &LookupFrameworkCache(StringRef FWName) {
420    return FrameworkMap[FWName];
421  }
422
423  /// Mark the specified file as a target of a \#include,
424  /// \#include_next, or \#import directive.
425  ///
426  /// \return false if \#including the file will have no effect or true
427  /// if we should include it.
428  bool ShouldEnterIncludeFile(Preprocessor &PPconst FileEntry *File,
429                              bool isImportbool ModulesEnabled,
430                              Module *M);
431
432  /// Return whether the specified file is a normal header,
433  /// a system header, or a C++ friendly system header.
434  SrcMgr::CharacteristicKind getFileDirFlavor(const FileEntry *File) {
435    return (SrcMgr::CharacteristicKind)getFileInfo(File).DirInfo;
436  }
437
438  /// Mark the specified file as a "once only" file, e.g. due to
439  /// \#pragma once.
440  void MarkFileIncludeOnce(const FileEntry *File) {
441    HeaderFileInfo &FI = getFileInfo(File);
442    FI.isImport = true;
443    FI.isPragmaOnce = true;
444  }
445
446  /// Mark the specified file as a system header, e.g. due to
447  /// \#pragma GCC system_header.
448  void MarkFileSystemHeader(const FileEntry *File) {
449    getFileInfo(File).DirInfo = SrcMgr::C_System;
450  }
451
452  /// Mark the specified file as part of a module.
453  void MarkFileModuleHeader(const FileEntry *FE,
454                            ModuleMap::ModuleHeaderRole Role,
455                            bool isCompilingModuleHeader);
456
457  /// Increment the count for the number of times the specified
458  /// FileEntry has been entered.
459  void IncrementIncludeCount(const FileEntry *File) {
460    ++getFileInfo(File).NumIncludes;
461  }
462
463  /// Mark the specified file as having a controlling macro.
464  ///
465  /// This is used by the multiple-include optimization to eliminate
466  /// no-op \#includes.
467  void SetFileControllingMacro(const FileEntry *File,
468                               const IdentifierInfo *ControllingMacro) {
469    getFileInfo(File).ControllingMacro = ControllingMacro;
470  }
471
472  /// Return true if this is the first time encountering this header.
473  bool FirstTimeLexingFile(const FileEntry *File) {
474    return getFileInfo(File).NumIncludes == 1;
475  }
476
477  /// Determine whether this file is intended to be safe from
478  /// multiple inclusions, e.g., it has \#pragma once or a controlling
479  /// macro.
480  ///
481  /// This routine does not consider the effect of \#import
482  bool isFileMultipleIncludeGuarded(const FileEntry *File);
483
484  /// This method returns a HeaderMap for the specified
485  /// FileEntry, uniquing them through the 'HeaderMaps' datastructure.
486  const HeaderMap *CreateHeaderMap(const FileEntry *FE);
487
488  /// Get filenames for all registered header maps.
489  void getHeaderMapFileNames(SmallVectorImpl<std::string> &Namesconst;
490
491  /// Retrieve the name of the cached module file that should be used
492  /// to load the given module.
493  ///
494  /// \param Module The module whose module file name will be returned.
495  ///
496  /// \returns The name of the module file that corresponds to this module,
497  /// or an empty string if this module does not correspond to any module file.
498  std::string getCachedModuleFileName(Module *Module);
499
500  /// Retrieve the name of the prebuilt module file that should be used
501  /// to load a module with the given name.
502  ///
503  /// \param ModuleName The module whose module file name will be returned.
504  ///
505  /// \param FileMapOnly If true, then only look in the explicit module name
506  //  to file name map and skip the directory search.
507  ///
508  /// \returns The name of the module file that corresponds to this module,
509  /// or an empty string if this module does not correspond to any module file.
510  std::string getPrebuiltModuleFileName(StringRef ModuleName,
511                                        bool FileMapOnly = false);
512
513  /// Retrieve the name of the (to-be-)cached module file that should
514  /// be used to load a module with the given name.
515  ///
516  /// \param ModuleName The module whose module file name will be returned.
517  ///
518  /// \param ModuleMapPath A path that when combined with \c ModuleName
519  /// uniquely identifies this module. See Module::ModuleMap.
520  ///
521  /// \returns The name of the module file that corresponds to this module,
522  /// or an empty string if this module does not correspond to any module file.
523  std::string getCachedModuleFileName(StringRef ModuleName,
524                                      StringRef ModuleMapPath);
525
526  /// Lookup a module Search for a module with the given name.
527  ///
528  /// \param ModuleName The name of the module we're looking for.
529  ///
530  /// \param AllowSearch Whether we are allowed to search in the various
531  /// search directories to produce a module definition. If not, this lookup
532  /// will only return an already-known module.
533  ///
534  /// \param AllowExtraModuleMapSearch Whether we allow to search modulemaps
535  /// in subdirectories.
536  ///
537  /// \returns The module with the given name.
538  Module *lookupModule(StringRef ModuleNamebool AllowSearch = true,
539                       bool AllowExtraModuleMapSearch = false);
540
541  /// Try to find a module map file in the given directory, returning
542  /// \c nullptr if none is found.
543  const FileEntry *lookupModuleMapFile(const DirectoryEntry *Dir,
544                                       bool IsFramework);
545
546  void IncrementFrameworkLookupCount() { ++NumFrameworkLookups; }
547
548  /// Determine whether there is a module map that may map the header
549  /// with the given file name to a (sub)module.
550  /// Always returns false if modules are disabled.
551  ///
552  /// \param Filename The name of the file.
553  ///
554  /// \param Root The "root" directory, at which we should stop looking for
555  /// module maps.
556  ///
557  /// \param IsSystem Whether the directories we're looking at are system
558  /// header directories.
559  bool hasModuleMap(StringRef Filenameconst DirectoryEntry *Root,
560                    bool IsSystem);
561
562  /// Retrieve the module that corresponds to the given file, if any.
563  ///
564  /// \param File The header that we wish to map to a module.
565  /// \param AllowTextual Whether we want to find textual headers too.
566  ModuleMap::KnownHeader findModuleForHeader(const FileEntry *File,
567                                             bool AllowTextual = falseconst;
568
569  /// Read the contents of the given module map file.
570  ///
571  /// \param File The module map file.
572  /// \param IsSystem Whether this file is in a system header directory.
573  /// \param ID If the module map file is already mapped (perhaps as part of
574  ///        processing a preprocessed module), the ID of the file.
575  /// \param Offset [inout] An offset within ID to start parsing. On exit,
576  ///        filled by the end of the parsed contents (either EOF or the
577  ///        location of an end-of-module-map pragma).
578  /// \param OriginalModuleMapFile The original path to the module map file,
579  ///        used to resolve paths within the module (this is required when
580  ///        building the module from preprocessed source).
581  /// \returns true if an error occurred, false otherwise.
582  bool loadModuleMapFile(const FileEntry *Filebool IsSystem,
583                         FileID ID = FileID(), unsigned *Offset = nullptr,
584                         StringRef OriginalModuleMapFile = StringRef());
585
586  /// Collect the set of all known, top-level modules.
587  ///
588  /// \param Modules Will be filled with the set of known, top-level modules.
589  void collectAllModules(SmallVectorImpl<Module *> &Modules);
590
591  /// Load all known, top-level system modules.
592  void loadTopLevelSystemModules();
593
594private:
595  /// Lookup a module with the given module name and search-name.
596  ///
597  /// \param ModuleName The name of the module we're looking for.
598  ///
599  /// \param SearchName The "search-name" to derive filesystem paths from
600  /// when looking for the module map; this is usually equal to ModuleName,
601  /// but for compatibility with some buggy frameworks, additional attempts
602  /// may be made to find the module under a related-but-different search-name.
603  ///
604  /// \param AllowExtraModuleMapSearch Whether we allow to search modulemaps
605  /// in subdirectories.
606  ///
607  /// \returns The module named ModuleName.
608  Module *lookupModule(StringRef ModuleNameStringRef SearchName,
609                       bool AllowExtraModuleMapSearch = false);
610
611  /// Retrieve a module with the given name, which may be part of the
612  /// given framework.
613  ///
614  /// \param Name The name of the module to retrieve.
615  ///
616  /// \param Dir The framework directory (e.g., ModuleName.framework).
617  ///
618  /// \param IsSystem Whether the framework directory is part of the system
619  /// frameworks.
620  ///
621  /// \returns The module, if found; otherwise, null.
622  Module *loadFrameworkModule(StringRef Name,
623                              const DirectoryEntry *Dir,
624                              bool IsSystem);
625
626  /// Load all of the module maps within the immediate subdirectories
627  /// of the given search directory.
628  void loadSubdirectoryModuleMaps(DirectoryLookup &SearchDir);
629
630  /// Find and suggest a usable module for the given file.
631  ///
632  /// \return \c true if the file can be used, \c false if we are not permitted to
633  ///         find this file due to requirements from \p RequestingModule.
634  bool findUsableModuleForHeader(const FileEntry *File,
635                                 const DirectoryEntry *Root,
636                                 Module *RequestingModule,
637                                 ModuleMap::KnownHeader *SuggestedModule,
638                                 bool IsSystemHeaderDir);
639
640  /// Find and suggest a usable module for the given file, which is part of
641  /// the specified framework.
642  ///
643  /// \return \c true if the file can be used, \c false if we are not permitted to
644  ///         find this file due to requirements from \p RequestingModule.
645  bool findUsableModuleForFrameworkHeader(
646      const FileEntry *FileStringRef FrameworkNameModule *RequestingModule,
647      ModuleMap::KnownHeader *SuggestedModulebool IsSystemFramework);
648
649  /// Look up the file with the specified name and determine its owning
650  /// module.
651  const FileEntry *
652  getFileAndSuggestModule(StringRef FileNameSourceLocation IncludeLoc,
653                          const DirectoryEntry *Dirbool IsSystemHeaderDir,
654                          Module *RequestingModule,
655                          ModuleMap::KnownHeader *SuggestedModule);
656
657public:
658  /// Retrieve the module map.
659  ModuleMap &getModuleMap() { return ModMap; }
660
661  /// Retrieve the module map.
662  const ModuleMap &getModuleMap() const { return ModMap; }
663
664  unsigned header_file_size() const { return FileInfo.size(); }
665
666  /// Return the HeaderFileInfo structure for the specified FileEntry,
667  /// in preparation for updating it in some way.
668  HeaderFileInfo &getFileInfo(const FileEntry *FE);
669
670  /// Return the HeaderFileInfo structure for the specified FileEntry,
671  /// if it has ever been filled in.
672  /// \param WantExternal Whether the caller wants purely-external header file
673  ///        info (where \p External is true).
674  const HeaderFileInfo *getExistingFileInfo(const FileEntry *FE,
675                                            bool WantExternal = trueconst;
676
677  // Used by external tools
678  using search_dir_iterator = std::vector<DirectoryLookup>::const_iterator;
679
680  search_dir_iterator search_dir_begin() const { return SearchDirs.begin(); }
681  search_dir_iterator search_dir_end() const { return SearchDirs.end(); }
682  unsigned search_dir_size() const { return SearchDirs.size(); }
683
684  search_dir_iterator quoted_dir_begin() const {
685    return SearchDirs.begin();
686  }
687
688  search_dir_iterator quoted_dir_end() const {
689    return SearchDirs.begin() + AngledDirIdx;
690  }
691
692  search_dir_iterator angled_dir_begin() const {
693    return SearchDirs.begin() + AngledDirIdx;
694  }
695
696  search_dir_iterator angled_dir_end() const {
697    return SearchDirs.begin() + SystemDirIdx;
698  }
699
700  search_dir_iterator system_dir_begin() const {
701    return SearchDirs.begin() + SystemDirIdx;
702  }
703
704  search_dir_iterator system_dir_end() const { return SearchDirs.end(); }
705
706  /// Retrieve a uniqued framework name.
707  StringRef getUniqueFrameworkName(StringRef Framework);
708
709  /// Suggest a path by which the specified file could be found, for
710  /// use in diagnostics to suggest a #include.
711  ///
712  /// \param IsSystem If non-null, filled in to indicate whether the suggested
713  ///        path is relative to a system header directory.
714  std::string suggestPathToFileForDiagnostics(const FileEntry *File,
715                                              bool *IsSystem = nullptr);
716
717  /// Suggest a path by which the specified file could be found, for
718  /// use in diagnostics to suggest a #include.
719  ///
720  /// \param WorkingDir If non-empty, this will be prepended to search directory
721  /// paths that are relative.
722  std::string suggestPathToFileForDiagnostics(llvm::StringRef File,
723                                              llvm::StringRef WorkingDir,
724                                              bool *IsSystem = nullptr);
725
726  void PrintStats();
727
728  size_t getTotalMemory() const;
729
730private:
731  /// Describes what happened when we tried to load a module map file.
732  enum LoadModuleMapResult {
733    /// The module map file had already been loaded.
734    LMM_AlreadyLoaded,
735
736    /// The module map file was loaded by this invocation.
737    LMM_NewlyLoaded,
738
739    /// There is was directory with the given name.
740    LMM_NoDirectory,
741
742    /// There was either no module map file or the module map file was
743    /// invalid.
744    LMM_InvalidModuleMap
745  };
746
747  LoadModuleMapResult loadModuleMapFileImpl(const FileEntry *File,
748                                            bool IsSystem,
749                                            const DirectoryEntry *Dir,
750                                            FileID ID = FileID(),
751                                            unsigned *Offset = nullptr);
752
753  /// Try to load the module map file in the given directory.
754  ///
755  /// \param DirName The name of the directory where we will look for a module
756  /// map file.
757  /// \param IsSystem Whether this is a system header directory.
758  /// \param IsFramework Whether this is a framework directory.
759  ///
760  /// \returns The result of attempting to load the module map file from the
761  /// named directory.
762  LoadModuleMapResult loadModuleMapFile(StringRef DirNamebool IsSystem,
763                                        bool IsFramework);
764
765  /// Try to load the module map file in the given directory.
766  ///
767  /// \param Dir The directory where we will look for a module map file.
768  /// \param IsSystem Whether this is a system header directory.
769  /// \param IsFramework Whether this is a framework directory.
770  ///
771  /// \returns The result of attempting to load the module map file from the
772  /// named directory.
773  LoadModuleMapResult loadModuleMapFile(const DirectoryEntry *Dir,
774                                        bool IsSystembool IsFramework);
775};
776
777// namespace clang
778
779#endif // LLVM_CLANG_LEX_HEADERSEARCH_H
780
clang::HeaderFileInfo::isImport
clang::HeaderFileInfo::isPragmaOnce
clang::HeaderFileInfo::DirInfo
clang::HeaderFileInfo::External
clang::HeaderFileInfo::isModuleHeader
clang::HeaderFileInfo::isCompilingModuleHeader
clang::HeaderFileInfo::Resolved
clang::HeaderFileInfo::IndexHeaderMapHeader
clang::HeaderFileInfo::IsValid
clang::HeaderFileInfo::NumIncludes
clang::HeaderFileInfo::ControllingMacroID
clang::HeaderFileInfo::ControllingMacro
clang::HeaderFileInfo::Framework
clang::HeaderFileInfo::getControllingMacro
clang::HeaderFileInfo::isNonDefault
clang::ExternalHeaderFileInfoSource::GetHeaderFileInfo
clang::FrameworkCacheEntry::Directory
clang::FrameworkCacheEntry::IsUserSpecifiedSystemFramework
clang::HeaderSearch::HSOpts
clang::HeaderSearch::Diags
clang::HeaderSearch::FileMgr
clang::HeaderSearch::SearchDirs
clang::HeaderSearch::AngledDirIdx
clang::HeaderSearch::SystemDirIdx
clang::HeaderSearch::NoCurDirSearch
clang::HeaderSearch::SystemHeaderPrefixes
clang::HeaderSearch::ModuleCachePath
clang::HeaderSearch::FileInfo
clang::HeaderSearch::LookupFileCacheInfo
clang::HeaderSearch::LookupFileCacheInfo::StartIdx
clang::HeaderSearch::LookupFileCacheInfo::HitIdx
clang::HeaderSearch::LookupFileCacheInfo::MappedName
clang::HeaderSearch::LookupFileCacheInfo::reset
clang::HeaderSearch::LookupFileCache
clang::HeaderSearch::FrameworkMap
clang::HeaderSearch::IncludeAliases
clang::HeaderSearch::HeaderMaps
clang::HeaderSearch::ModMap
clang::HeaderSearch::DirectoryHasModuleMap
clang::HeaderSearch::LoadedModuleMaps
clang::HeaderSearch::FrameworkNames
clang::HeaderSearch::ExternalLookup
clang::HeaderSearch::ExternalSource
clang::HeaderSearch::NumIncluded
clang::HeaderSearch::NumMultiIncludeFileOptzn
clang::HeaderSearch::NumFrameworkLookups
clang::HeaderSearch::NumSubFrameworkLookups
clang::HeaderSearch::getHeaderSearchOpts
clang::HeaderSearch::getFileMgr
clang::HeaderSearch::getDiags
clang::HeaderSearch::SetSearchPaths
clang::HeaderSearch::AddSearchPath
clang::HeaderSearch::SetSystemHeaderPrefixes
clang::HeaderSearch::HasIncludeAliasMap
clang::HeaderSearch::AddIncludeAlias
clang::HeaderSearch::MapHeaderToIncludeAlias
clang::HeaderSearch::setModuleCachePath
clang::HeaderSearch::getModuleCachePath
clang::HeaderSearch::setDirectoryHasModuleMap
clang::HeaderSearch::ClearFileInfo
clang::HeaderSearch::SetExternalLookup
clang::HeaderSearch::getExternalLookup
clang::HeaderSearch::SetExternalSource
clang::HeaderSearch::setTarget
clang::HeaderSearch::LookupFile
clang::HeaderSearch::LookupSubframeworkHeader
clang::HeaderSearch::LookupFrameworkCache
clang::HeaderSearch::ShouldEnterIncludeFile
clang::HeaderSearch::getFileDirFlavor
clang::HeaderSearch::MarkFileIncludeOnce
clang::HeaderSearch::MarkFileSystemHeader
clang::HeaderSearch::MarkFileModuleHeader
clang::HeaderSearch::IncrementIncludeCount
clang::HeaderSearch::SetFileControllingMacro
clang::HeaderSearch::FirstTimeLexingFile
clang::HeaderSearch::isFileMultipleIncludeGuarded
clang::HeaderSearch::CreateHeaderMap
clang::HeaderSearch::getHeaderMapFileNames
clang::HeaderSearch::getCachedModuleFileName
clang::HeaderSearch::getPrebuiltModuleFileName
clang::HeaderSearch::getCachedModuleFileName
clang::HeaderSearch::lookupModule
clang::HeaderSearch::lookupModuleMapFile
clang::HeaderSearch::IncrementFrameworkLookupCount
clang::HeaderSearch::hasModuleMap
clang::HeaderSearch::findModuleForHeader
clang::HeaderSearch::loadModuleMapFile
clang::HeaderSearch::collectAllModules
clang::HeaderSearch::loadTopLevelSystemModules
clang::HeaderSearch::lookupModule
clang::HeaderSearch::loadFrameworkModule
clang::HeaderSearch::loadSubdirectoryModuleMaps
clang::HeaderSearch::findUsableModuleForHeader
clang::HeaderSearch::findUsableModuleForFrameworkHeader
clang::HeaderSearch::getFileAndSuggestModule
clang::HeaderSearch::getModuleMap
clang::HeaderSearch::getModuleMap
clang::HeaderSearch::header_file_size
clang::HeaderSearch::getFileInfo
clang::HeaderSearch::getExistingFileInfo
clang::HeaderSearch::search_dir_begin
clang::HeaderSearch::search_dir_end
clang::HeaderSearch::search_dir_size
clang::HeaderSearch::quoted_dir_begin
clang::HeaderSearch::quoted_dir_end
clang::HeaderSearch::angled_dir_begin
clang::HeaderSearch::angled_dir_end
clang::HeaderSearch::system_dir_begin
clang::HeaderSearch::system_dir_end
clang::HeaderSearch::getUniqueFrameworkName
clang::HeaderSearch::suggestPathToFileForDiagnostics
clang::HeaderSearch::suggestPathToFileForDiagnostics
clang::HeaderSearch::PrintStats
clang::HeaderSearch::getTotalMemory
clang::HeaderSearch::LoadModuleMapResult
clang::HeaderSearch::loadModuleMapFileImpl
clang::HeaderSearch::loadModuleMapFile
clang::HeaderSearch::loadModuleMapFile