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 
34 namespace clang {
35 
36 class DiagnosticsEngine;
37 class DirectoryEntry;
38 class ExternalPreprocessorSource;
39 class FileEntry;
40 class FileManager;
41 class HeaderSearchOptions;
42 class IdentifierInfo;
43 class LangOptions;
44 class Module;
45 class Preprocessor;
46 class TargetInfo;
47 
48 /// The preprocessor keeps track of this information for each
49 /// file that is \#included.
50 struct 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.
133 class ExternalHeaderFileInfoSource {
134 public:
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.
146 struct 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.
158 class HeaderSearch {
159   friend class DirectoryLookup;
160 
161   /// Header-search options used to initialize this header search.
162   std::shared_ptr<HeaderSearchOptions> HSOpts;
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<DirectoryLookup> SearchDirs;
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::string, bool>> 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<HeaderFileInfo> FileInfo;
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 *, bool> DirectoryHasModuleMap;
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 *, bool> LoadedModuleMaps;
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 public:
254   HeaderSearch(std::shared_ptr<HeaderSearchOptions> HSOpts,
255                SourceManager &SourceMgr, DiagnosticsEngine &Diags,
256                const LangOptions &LangOpts, const TargetInfo *Target);
257   HeaderSearch(const HeaderSearch &) = delete;
258   HeaderSearch &operator=(const HeaderSearch &) = delete;
259 
260   /// Retrieve the header-search options with which this header search
261   /// was initialized.
262   HeaderSearchOptions &getHeaderSearchOpts() const { return *HSOpts; }
263 
264   FileManager &getFileMgr() const { return FileMgr; }
265 
266   DiagnosticsEngine &getDiags() const { return Diags; }
267 
268   /// Interface for setting the file search paths.
269   void SetSearchPaths(const std::vector<DirectoryLookup> &dirs,
270                       unsigned angledDirIdx, unsigned systemDirIdx,
271                       bool noCurDirSearch) {
272     assert(angledDirIdx <= systemDirIdx && systemDirIdx <= dirs.size() &&
273         "Directory indices are unordered");
274     SearchDirs = dirs;
275     AngledDirIdx = angledDirIdx;
276     SystemDirIdx = systemDirIdx;
277     NoCurDirSearch = noCurDirSearch;
278     //LookupFileCache.clear();
279   }
280 
281   /// Add an additional search path.
282   void AddSearchPath(const DirectoryLookup &dir, bool isAngled) {
283     unsigned idx = isAngled ? SystemDirIdx : AngledDirIdx;
284     SearchDirs.insert(SearchDirs.begin() + idx, dir);
285     if (!isAngled)
286       AngledDirIdx++;
287     SystemDirIdx++;
288   }
289 
290   /// Set the list of system header prefixes.
291   void SetSystemHeaderPrefixes(ArrayRef<std::pair<std::string, bool>> P) {
292     SystemHeaderPrefixes.assign(P.begin(), P.end());
293   }
294 
295   /// Checks whether the map exists or not.
296   bool HasIncludeAliasMap() const { return (bool)IncludeAliases; }
297 
298   /// Map the source include name to the dest include name.
299   ///
300   /// The Source should include the angle brackets or quotes, the dest
301   /// should not.  This allows for distinction between <> and "" headers.
302   void AddIncludeAlias(StringRef Source, StringRef Dest) {
303     if (!IncludeAliases)
304       IncludeAliases.reset(new IncludeAliasMap);
305     (*IncludeAliases)[Source] = std::string(Dest);
306   }
307 
308   /// Maps one header file name to a different header
309   /// file name, for use with the include_alias pragma.  Note that the source
310   /// file name should include the angle brackets or quotes.  Returns StringRef
311   /// as null if the header cannot be mapped.
312   StringRef MapHeaderToIncludeAlias(StringRef Source) {
313     assert(IncludeAliases && "Trying to map headers when there's no map");
314 
315     // Do any filename replacements before anything else
316     IncludeAliasMap::const_iterator Iter = IncludeAliases->find(Source);
317     if (Iter != IncludeAliases->end())
318       return Iter->second;
319     return {};
320   }
321 
322   /// Set the path to the module cache.
323   void setModuleCachePath(StringRef CachePath) {
324     ModuleCachePath = std::string(CachePath);
325   }
326 
327   /// Retrieve the path to the module cache.
328   StringRef getModuleCachePath() const { return ModuleCachePath; }
329 
330   /// Consider modules when including files from this directory.
331   void setDirectoryHasModuleMap(const DirectoryEntry* Dir) {
332     DirectoryHasModuleMap[Dir] = true;
333   }
334 
335   /// Forget everything we know about headers so far.
336   void ClearFileInfo() {
337     FileInfo.clear();
338   }
339 
340   void SetExternalLookup(ExternalPreprocessorSource *EPS) {
341     ExternalLookup = EPS;
342   }
343 
344   ExternalPreprocessorSource *getExternalLookup() const {
345     return ExternalLookup;
346   }
347 
348   /// Set the external source of header information.
349   void SetExternalSource(ExternalHeaderFileInfoSource *ES) {
350     ExternalSource = ES;
351   }
352 
353   /// Set the target information for the header search, if not
354   /// already known.
355   void setTarget(const TargetInfo &Target);
356 
357   /// Given a "foo" or \<foo> reference, look up the indicated file,
358   /// return null on failure.
359   ///
360   /// \returns If successful, this returns 'UsedDir', the DirectoryLookup member
361   /// the file was found in, or null if not applicable.
362   ///
363   /// \param IncludeLoc Used for diagnostics if valid.
364   ///
365   /// \param isAngled indicates whether the file reference is a <> reference.
366   ///
367   /// \param CurDir If non-null, the file was found in the specified directory
368   /// search location.  This is used to implement \#include_next.
369   ///
370   /// \param Includers Indicates where the \#including file(s) are, in case
371   /// relative searches are needed. In reverse order of inclusion.
372   ///
373   /// \param SearchPath If non-null, will be set to the search path relative
374   /// to which the file was found. If the include path is absolute, SearchPath
375   /// will be set to an empty string.
376   ///
377   /// \param RelativePath If non-null, will be set to the path relative to
378   /// SearchPath at which the file was found. This only differs from the
379   /// Filename for framework includes.
380   ///
381   /// \param SuggestedModule If non-null, and the file found is semantically
382   /// part of a known module, this will be set to the module that should
383   /// be imported instead of preprocessing/parsing the file found.
384   ///
385   /// \param IsMapped If non-null, and the search involved header maps, set to
386   /// true.
387   ///
388   /// \param IsFrameworkFound If non-null, will be set to true if a framework is
389   /// found in any of searched SearchDirs. Will be set to false if a framework
390   /// is found only through header maps. Doesn't guarantee the requested file is
391   /// found.
392   Optional<FileEntryRef> LookupFile(
393       StringRef Filename, SourceLocation IncludeLoc, bool isAngled,
394       const DirectoryLookup *FromDir, const DirectoryLookup *&CurDir,
395       ArrayRef<std::pair<const FileEntry *, const DirectoryEntry *>> Includers,
396       SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
397       Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule,
398       bool *IsMapped, bool *IsFrameworkFound, bool SkipCache = false,
399       bool BuildSystemModule = false);
400 
401   /// Look up a subframework for the specified \#include file.
402   ///
403   /// For example, if \#include'ing <HIToolbox/HIToolbox.h> from
404   /// within ".../Carbon.framework/Headers/Carbon.h", check to see if
405   /// HIToolbox is a subframework within Carbon.framework.  If so, return
406   /// the FileEntry for the designated file, otherwise return null.
407   Optional<FileEntryRef> LookupSubframeworkHeader(
408       StringRef Filename, const FileEntry *ContextFileEnt,
409       SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
410       Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule);
411 
412   /// Look up the specified framework name in our framework cache.
413   /// \returns The DirectoryEntry it is in if we know, null otherwise.
414   FrameworkCacheEntry &LookupFrameworkCache(StringRef FWName) {
415     return FrameworkMap[FWName];
416   }
417 
418   /// Mark the specified file as a target of a \#include,
419   /// \#include_next, or \#import directive.
420   ///
421   /// \return false if \#including the file will have no effect or true
422   /// if we should include it.
423   bool ShouldEnterIncludeFile(Preprocessor &PP, const FileEntry *File,
424                               bool isImport, bool ModulesEnabled,
425                               Module *M);
426 
427   /// Return whether the specified file is a normal header,
428   /// a system header, or a C++ friendly system header.
429   SrcMgr::CharacteristicKind getFileDirFlavor(const FileEntry *File) {
430     return (SrcMgr::CharacteristicKind)getFileInfo(File).DirInfo;
431   }
432 
433   /// Mark the specified file as a "once only" file, e.g. due to
434   /// \#pragma once.
435   void MarkFileIncludeOnce(const FileEntry *File) {
436     HeaderFileInfo &FI = getFileInfo(File);
437     FI.isImport = true;
438     FI.isPragmaOnce = true;
439   }
440 
441   /// Mark the specified file as a system header, e.g. due to
442   /// \#pragma GCC system_header.
443   void MarkFileSystemHeader(const FileEntry *File) {
444     getFileInfo(File).DirInfo = SrcMgr::C_System;
445   }
446 
447   /// Mark the specified file as part of a module.
448   void MarkFileModuleHeader(const FileEntry *FE,
449                             ModuleMap::ModuleHeaderRole Role,
450                             bool isCompilingModuleHeader);
451 
452   /// Increment the count for the number of times the specified
453   /// FileEntry has been entered.
454   void IncrementIncludeCount(const FileEntry *File) {
455     ++getFileInfo(File).NumIncludes;
456   }
457 
458   /// Mark the specified file as having a controlling macro.
459   ///
460   /// This is used by the multiple-include optimization to eliminate
461   /// no-op \#includes.
462   void SetFileControllingMacro(const FileEntry *File,
463                                const IdentifierInfo *ControllingMacro) {
464     getFileInfo(File).ControllingMacro = ControllingMacro;
465   }
466 
467   /// Return true if this is the first time encountering this header.
468   bool FirstTimeLexingFile(const FileEntry *File) {
469     return getFileInfo(File).NumIncludes == 1;
470   }
471 
472   /// Determine whether this file is intended to be safe from
473   /// multiple inclusions, e.g., it has \#pragma once or a controlling
474   /// macro.
475   ///
476   /// This routine does not consider the effect of \#import
477   bool isFileMultipleIncludeGuarded(const FileEntry *File);
478 
479   /// Determine whether the given file is known to have ever been \#imported
480   /// (or if it has been \#included and we've encountered a \#pragma once).
481   bool hasFileBeenImported(const FileEntry *File) {
482     const HeaderFileInfo *FI = getExistingFileInfo(File);
483     return FI && FI->isImport;
484   }
485 
486   /// This method returns a HeaderMap for the specified
487   /// FileEntry, uniquing them through the 'HeaderMaps' datastructure.
488   const HeaderMap *CreateHeaderMap(const FileEntry *FE);
489 
490   /// Get filenames for all registered header maps.
491   void getHeaderMapFileNames(SmallVectorImpl<std::string> &Names) const;
492 
493   /// Retrieve the name of the cached module file that should be used
494   /// to load the given module.
495   ///
496   /// \param Module The module whose module file name will be returned.
497   ///
498   /// \returns The name of the module file that corresponds to this module,
499   /// or an empty string if this module does not correspond to any module file.
500   std::string getCachedModuleFileName(Module *Module);
501 
502   /// Retrieve the name of the prebuilt module file that should be used
503   /// to load a module with the given name.
504   ///
505   /// \param ModuleName The module whose module file name will be returned.
506   ///
507   /// \param FileMapOnly If true, then only look in the explicit module name
508   //  to file name map and skip the directory search.
509   ///
510   /// \returns The name of the module file that corresponds to this module,
511   /// or an empty string if this module does not correspond to any module file.
512   std::string getPrebuiltModuleFileName(StringRef ModuleName,
513                                         bool FileMapOnly = false);
514 
515   /// Retrieve the name of the (to-be-)cached module file that should
516   /// be used to load a module with the given name.
517   ///
518   /// \param ModuleName The module whose module file name will be returned.
519   ///
520   /// \param ModuleMapPath A path that when combined with \c ModuleName
521   /// uniquely identifies this module. See Module::ModuleMap.
522   ///
523   /// \returns The name of the module file that corresponds to this module,
524   /// or an empty string if this module does not correspond to any module file.
525   std::string getCachedModuleFileName(StringRef ModuleName,
526                                       StringRef ModuleMapPath);
527 
528   /// Lookup a module Search for a module with the given name.
529   ///
530   /// \param ModuleName The name of the module we're looking for.
531   ///
532   /// \param AllowSearch Whether we are allowed to search in the various
533   /// search directories to produce a module definition. If not, this lookup
534   /// will only return an already-known module.
535   ///
536   /// \param AllowExtraModuleMapSearch Whether we allow to search modulemaps
537   /// in subdirectories.
538   ///
539   /// \returns The module with the given name.
540   Module *lookupModule(StringRef ModuleName, bool AllowSearch = true,
541                        bool AllowExtraModuleMapSearch = false);
542 
543   /// Try to find a module map file in the given directory, returning
544   /// \c nullptr if none is found.
545   const FileEntry *lookupModuleMapFile(const DirectoryEntry *Dir,
546                                        bool IsFramework);
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 Filename, const 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 = false) const;
568 
569   /// Retrieve all the modules corresponding to the given file.
570   ///
571   /// \ref findModuleForHeader should typically be used instead of this.
572   ArrayRef<ModuleMap::KnownHeader>
573   findAllModulesForHeader(const FileEntry *File) const;
574 
575   /// Read the contents of the given module map file.
576   ///
577   /// \param File The module map file.
578   /// \param IsSystem Whether this file is in a system header directory.
579   /// \param ID If the module map file is already mapped (perhaps as part of
580   ///        processing a preprocessed module), the ID of the file.
581   /// \param Offset [inout] An offset within ID to start parsing. On exit,
582   ///        filled by the end of the parsed contents (either EOF or the
583   ///        location of an end-of-module-map pragma).
584   /// \param OriginalModuleMapFile The original path to the module map file,
585   ///        used to resolve paths within the module (this is required when
586   ///        building the module from preprocessed source).
587   /// \returns true if an error occurred, false otherwise.
588   bool loadModuleMapFile(const FileEntry *File, bool IsSystem,
589                          FileID ID = FileID(), unsigned *Offset = nullptr,
590                          StringRef OriginalModuleMapFile = StringRef());
591 
592   /// Collect the set of all known, top-level modules.
593   ///
594   /// \param Modules Will be filled with the set of known, top-level modules.
595   void collectAllModules(SmallVectorImpl<Module *> &Modules);
596 
597   /// Load all known, top-level system modules.
598   void loadTopLevelSystemModules();
599 
600 private:
601   /// Lookup a module with the given module name and search-name.
602   ///
603   /// \param ModuleName The name of the module we're looking for.
604   ///
605   /// \param SearchName The "search-name" to derive filesystem paths from
606   /// when looking for the module map; this is usually equal to ModuleName,
607   /// but for compatibility with some buggy frameworks, additional attempts
608   /// may be made to find the module under a related-but-different search-name.
609   ///
610   /// \param AllowExtraModuleMapSearch Whether we allow to search modulemaps
611   /// in subdirectories.
612   ///
613   /// \returns The module named ModuleName.
614   Module *lookupModule(StringRef ModuleName, StringRef SearchName,
615                        bool AllowExtraModuleMapSearch = false);
616 
617   /// Retrieve a module with the given name, which may be part of the
618   /// given framework.
619   ///
620   /// \param Name The name of the module to retrieve.
621   ///
622   /// \param Dir The framework directory (e.g., ModuleName.framework).
623   ///
624   /// \param IsSystem Whether the framework directory is part of the system
625   /// frameworks.
626   ///
627   /// \returns The module, if found; otherwise, null.
628   Module *loadFrameworkModule(StringRef Name,
629                               const DirectoryEntry *Dir,
630                               bool IsSystem);
631 
632   /// Load all of the module maps within the immediate subdirectories
633   /// of the given search directory.
634   void loadSubdirectoryModuleMaps(DirectoryLookup &SearchDir);
635 
636   /// Find and suggest a usable module for the given file.
637   ///
638   /// \return \c true if the file can be used, \c false if we are not permitted to
639   ///         find this file due to requirements from \p RequestingModule.
640   bool findUsableModuleForHeader(const FileEntry *File,
641                                  const DirectoryEntry *Root,
642                                  Module *RequestingModule,
643                                  ModuleMap::KnownHeader *SuggestedModule,
644                                  bool IsSystemHeaderDir);
645 
646   /// Find and suggest a usable module for the given file, which is part of
647   /// the specified framework.
648   ///
649   /// \return \c true if the file can be used, \c false if we are not permitted to
650   ///         find this file due to requirements from \p RequestingModule.
651   bool findUsableModuleForFrameworkHeader(
652       const FileEntry *File, StringRef FrameworkName, Module *RequestingModule,
653       ModuleMap::KnownHeader *SuggestedModule, bool IsSystemFramework);
654 
655   /// Look up the file with the specified name and determine its owning
656   /// module.
657   Optional<FileEntryRef>
658   getFileAndSuggestModule(StringRef FileName, SourceLocation IncludeLoc,
659                           const DirectoryEntry *Dir, bool IsSystemHeaderDir,
660                           Module *RequestingModule,
661                           ModuleMap::KnownHeader *SuggestedModule);
662 
663 public:
664   /// Retrieve the module map.
665   ModuleMap &getModuleMap() { return ModMap; }
666 
667   /// Retrieve the module map.
668   const ModuleMap &getModuleMap() const { return ModMap; }
669 
670   unsigned header_file_size() const { return FileInfo.size(); }
671 
672   /// Return the HeaderFileInfo structure for the specified FileEntry,
673   /// in preparation for updating it in some way.
674   HeaderFileInfo &getFileInfo(const FileEntry *FE);
675 
676   /// Return the HeaderFileInfo structure for the specified FileEntry,
677   /// if it has ever been filled in.
678   /// \param WantExternal Whether the caller wants purely-external header file
679   ///        info (where \p External is true).
680   const HeaderFileInfo *getExistingFileInfo(const FileEntry *FE,
681                                             bool WantExternal = true) const;
682 
683   // Used by external tools
684   using search_dir_iterator = std::vector<DirectoryLookup>::const_iterator;
685 
686   search_dir_iterator search_dir_begin() const { return SearchDirs.begin(); }
687   search_dir_iterator search_dir_end() const { return SearchDirs.end(); }
688   unsigned search_dir_size() const { return SearchDirs.size(); }
689 
690   search_dir_iterator quoted_dir_begin() const {
691     return SearchDirs.begin();
692   }
693 
694   search_dir_iterator quoted_dir_end() const {
695     return SearchDirs.begin() + AngledDirIdx;
696   }
697 
698   search_dir_iterator angled_dir_begin() const {
699     return SearchDirs.begin() + AngledDirIdx;
700   }
701 
702   search_dir_iterator angled_dir_end() const {
703     return SearchDirs.begin() + SystemDirIdx;
704   }
705 
706   search_dir_iterator system_dir_begin() const {
707     return SearchDirs.begin() + SystemDirIdx;
708   }
709 
710   search_dir_iterator system_dir_end() const { return SearchDirs.end(); }
711 
712   /// Retrieve a uniqued framework name.
713   StringRef getUniqueFrameworkName(StringRef Framework);
714 
715   /// Suggest a path by which the specified file could be found, for use in
716   /// diagnostics to suggest a #include. Returned path will only contain forward
717   /// slashes as separators. MainFile is the absolute path of the file that we
718   /// are generating the diagnostics for. It will try to shorten the path using
719   /// MainFile location, if none of the include search directories were prefix
720   /// of File.
721   ///
722   /// \param IsSystem If non-null, filled in to indicate whether the suggested
723   ///        path is relative to a system header directory.
724   std::string suggestPathToFileForDiagnostics(const FileEntry *File,
725                                               llvm::StringRef MainFile,
726                                               bool *IsSystem = nullptr);
727 
728   /// Suggest a path by which the specified file could be found, for use in
729   /// diagnostics to suggest a #include. Returned path will only contain forward
730   /// slashes as separators. MainFile is the absolute path of the file that we
731   /// are generating the diagnostics for. It will try to shorten the path using
732   /// MainFile location, if none of the include search directories were prefix
733   /// of File.
734   ///
735   /// \param WorkingDir If non-empty, this will be prepended to search directory
736   /// paths that are relative.
737   std::string suggestPathToFileForDiagnostics(llvm::StringRef File,
738                                               llvm::StringRef WorkingDir,
739                                               llvm::StringRef MainFile,
740                                               bool *IsSystem = nullptr);
741 
742   void PrintStats();
743 
744   size_t getTotalMemory() const;
745 
746 private:
747   /// Describes what happened when we tried to load a module map file.
748   enum LoadModuleMapResult {
749     /// The module map file had already been loaded.
750     LMM_AlreadyLoaded,
751 
752     /// The module map file was loaded by this invocation.
753     LMM_NewlyLoaded,
754 
755     /// There is was directory with the given name.
756     LMM_NoDirectory,
757 
758     /// There was either no module map file or the module map file was
759     /// invalid.
760     LMM_InvalidModuleMap
761   };
762 
763   LoadModuleMapResult loadModuleMapFileImpl(const FileEntry *File,
764                                             bool IsSystem,
765                                             const DirectoryEntry *Dir,
766                                             FileID ID = FileID(),
767                                             unsigned *Offset = nullptr);
768 
769   /// Try to load the module map file in the given directory.
770   ///
771   /// \param DirName The name of the directory where we will look for a module
772   /// map file.
773   /// \param IsSystem Whether this is a system header directory.
774   /// \param IsFramework Whether this is a framework directory.
775   ///
776   /// \returns The result of attempting to load the module map file from the
777   /// named directory.
778   LoadModuleMapResult loadModuleMapFile(StringRef DirName, bool IsSystem,
779                                         bool IsFramework);
780 
781   /// Try to load the module map file in the given directory.
782   ///
783   /// \param Dir The directory where we will look for a module map file.
784   /// \param IsSystem Whether this is a system header directory.
785   /// \param IsFramework Whether this is a framework directory.
786   ///
787   /// \returns The result of attempting to load the module map file from the
788   /// named directory.
789   LoadModuleMapResult loadModuleMapFile(const DirectoryEntry *Dir,
790                                         bool IsSystem, bool IsFramework);
791 };
792 
793 } // namespace clang
794 
795 #endif // LLVM_CLANG_LEX_HEADERSEARCH_H
796