Warning: This file is not a C or C++ file. It does not have highlighting.

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/SmallString.h"
24#include "llvm/ADT/StringMap.h"
25#include "llvm/ADT/StringRef.h"
26#include "llvm/ADT/StringSet.h"
27#include "llvm/Support/Allocator.h"
28#include <cassert>
29#include <cstddef>
30#include <memory>
31#include <string>
32#include <utility>
33#include <vector>
34
35namespace llvm {
36
37class Triple;
38
39} // namespace llvm
40
41namespace clang {
42
43class DiagnosticsEngine;
44class DirectoryEntry;
45class ExternalPreprocessorSource;
46class FileEntry;
47class FileManager;
48class HeaderSearch;
49class HeaderSearchOptions;
50class IdentifierInfo;
51class LangOptions;
52class Module;
53class Preprocessor;
54class TargetInfo;
55
56/// The preprocessor keeps track of this information for each
57/// file that is \#included.
58struct HeaderFileInfo {
59 // TODO: Whether the file was imported is not a property of the file itself.
60 // It's a preprocessor state, move it there.
61 /// True if this is a \#import'd file.
62 unsigned isImport : 1;
63
64 /// True if this is a \#pragma once file.
65 unsigned isPragmaOnce : 1;
66
67 /// Keep track of whether this is a system header, and if so,
68 /// whether it is C++ clean or not. This can be set by the include paths or
69 /// by \#pragma gcc system_header. This is an instance of
70 /// SrcMgr::CharacteristicKind.
71 unsigned DirInfo : 3;
72
73 /// Whether this header file info was supplied by an external source,
74 /// and has not changed since.
75 unsigned External : 1;
76
77 /// Whether this header is part of a module.
78 unsigned isModuleHeader : 1;
79
80 /// Whether this header is part of the module that we are building.
81 unsigned isCompilingModuleHeader : 1;
82
83 /// Whether this structure is considered to already have been
84 /// "resolved", meaning that it was loaded from the external source.
85 unsigned Resolved : 1;
86
87 /// Whether this is a header inside a framework that is currently
88 /// being built.
89 ///
90 /// When a framework is being built, the headers have not yet been placed
91 /// into the appropriate framework subdirectories, and therefore are
92 /// provided via a header map. This bit indicates when this is one of
93 /// those framework headers.
94 unsigned IndexHeaderMapHeader : 1;
95
96 /// Whether this file has been looked up as a header.
97 unsigned IsValid : 1;
98
99 /// The ID number of the controlling macro.
100 ///
101 /// This ID number will be non-zero when there is a controlling
102 /// macro whose IdentifierInfo may not yet have been loaded from
103 /// external storage.
104 unsigned ControllingMacroID = 0;
105
106 /// If this file has a \#ifndef XXX (or equivalent) guard that
107 /// protects the entire contents of the file, this is the identifier
108 /// for the macro that controls whether or not it has any effect.
109 ///
110 /// Note: Most clients should use getControllingMacro() to access
111 /// the controlling macro of this header, since
112 /// getControllingMacro() is able to load a controlling macro from
113 /// external storage.
114 const IdentifierInfo *ControllingMacro = nullptr;
115
116 /// If this header came from a framework include, this is the name
117 /// of the framework.
118 StringRef Framework;
119
120 HeaderFileInfo()
121 : isImport(false), isPragmaOnce(false), DirInfo(SrcMgr::C_User),
122 External(false), isModuleHeader(false), isCompilingModuleHeader(false),
123 Resolved(false), IndexHeaderMapHeader(false), IsValid(false) {}
124
125 /// Retrieve the controlling macro for this header file, if
126 /// any.
127 const IdentifierInfo *
128 getControllingMacro(ExternalPreprocessorSource *External);
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 Optional<DirectoryEntryRef> 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
156namespace detail {
157template <bool Const, typename T>
158using Qualified = std::conditional_t<Const, const T, T>;
159
160/// Forward iterator over the search directories of \c HeaderSearch.
161template <bool IsConst>
162struct SearchDirIteratorImpl
163 : llvm::iterator_facade_base<SearchDirIteratorImpl<IsConst>,
164 std::forward_iterator_tag,
165 Qualified<IsConst, DirectoryLookup>> {
166 /// Const -> non-const iterator conversion.
167 template <typename Enable = std::enable_if<IsConst, bool>>
168 SearchDirIteratorImpl(const SearchDirIteratorImpl<false> &Other)
169 : HS(Other.HS), Idx(Other.Idx) {}
170
171 SearchDirIteratorImpl(const SearchDirIteratorImpl &) = default;
172
173 SearchDirIteratorImpl &operator=(const SearchDirIteratorImpl &) = default;
174
175 bool operator==(const SearchDirIteratorImpl &RHS) const {
176 return HS == RHS.HS && Idx == RHS.Idx;
177 }
178
179 SearchDirIteratorImpl &operator++() {
180 assert(*this && "Invalid iterator.");
181 ++Idx;
182 return *this;
183 }
184
185 Qualified<IsConst, DirectoryLookup> &operator*() const {
186 assert(*this && "Invalid iterator.");
187 return HS->SearchDirs[Idx];
188 }
189
190 /// Creates an invalid iterator.
191 SearchDirIteratorImpl(std::nullptr_t) : HS(nullptr), Idx(0) {}
192
193 /// Checks whether the iterator is valid.
194 explicit operator bool() const { return HS != nullptr; }
195
196private:
197 /// The parent \c HeaderSearch. This is \c nullptr for invalid iterator.
198 Qualified<IsConst, HeaderSearch> *HS;
199
200 /// The index of the current element.
201 size_t Idx;
202
203 /// The constructor that creates a valid iterator.
204 SearchDirIteratorImpl(Qualified<IsConst, HeaderSearch> &HS, size_t Idx)
205 : HS(&HS), Idx(Idx) {}
206
207 /// Only HeaderSearch is allowed to instantiate valid iterators.
208 friend HeaderSearch;
209
210 /// Enables const -> non-const conversion.
211 friend SearchDirIteratorImpl<!IsConst>;
212};
213} // namespace detail
214
215using ConstSearchDirIterator = detail::SearchDirIteratorImpl<true>;
216using SearchDirIterator = detail::SearchDirIteratorImpl<false>;
217
218using ConstSearchDirRange = llvm::iterator_range<ConstSearchDirIterator>;
219using SearchDirRange = llvm::iterator_range<SearchDirIterator>;
220
221/// Encapsulates the information needed to find the file referenced
222/// by a \#include or \#include_next, (sub-)framework lookup, etc.
223class HeaderSearch {
224 friend class DirectoryLookup;
225
226 friend ConstSearchDirIterator;
227 friend SearchDirIterator;
228
229 /// Header-search options used to initialize this header search.
230 std::shared_ptr<HeaderSearchOptions> HSOpts;
231
232 /// Mapping from SearchDir to HeaderSearchOptions::UserEntries indices.
233 llvm::DenseMap<unsigned, unsigned> SearchDirToHSEntry;
234
235 DiagnosticsEngine &Diags;
236 FileManager &FileMgr;
237
238 /// \#include search path information. Requests for \#include "x" search the
239 /// directory of the \#including file first, then each directory in SearchDirs
240 /// consecutively. Requests for <x> search the current dir first, then each
241 /// directory in SearchDirs, starting at AngledDirIdx, consecutively. If
242 /// NoCurDirSearch is true, then the check for the file in the current
243 /// directory is suppressed.
244 std::vector<DirectoryLookup> SearchDirs;
245 /// Whether the DirectoryLookup at the corresponding index in SearchDirs has
246 /// been successfully used to lookup a file.
247 std::vector<bool> SearchDirsUsage;
248 unsigned AngledDirIdx = 0;
249 unsigned SystemDirIdx = 0;
250 bool NoCurDirSearch = false;
251
252 /// \#include prefixes for which the 'system header' property is
253 /// overridden.
254 ///
255 /// For a \#include "x" or \#include \<x> directive, the last string in this
256 /// list which is a prefix of 'x' determines whether the file is treated as
257 /// a system header.
258 std::vector<std::pair<std::string, bool>> SystemHeaderPrefixes;
259
260 /// The hash used for module cache paths.
261 std::string ModuleHash;
262
263 /// The path to the module cache.
264 std::string ModuleCachePath;
265
266 /// All of the preprocessor-specific data about files that are
267 /// included, indexed by the FileEntry's UID.
268 mutable std::vector<HeaderFileInfo> FileInfo;
269
270 /// Keeps track of each lookup performed by LookupFile.
271 struct LookupFileCacheInfo {
272 /// Starting search directory iterator that the cached search was performed
273 /// from. If there is a hit and this value doesn't match the current query,
274 /// the cache has to be ignored.
275 ConstSearchDirIterator StartIt = nullptr;
276
277 /// The search directory iterator that satisfied the query.
278 ConstSearchDirIterator HitIt = nullptr;
279
280 /// This is non-null if the original filename was mapped to a framework
281 /// include via a headermap.
282 const char *MappedName = nullptr;
283
284 /// Default constructor -- Initialize all members with zero.
285 LookupFileCacheInfo() = default;
286
287 void reset(ConstSearchDirIterator NewStartIt) {
288 StartIt = NewStartIt;
289 MappedName = nullptr;
290 }
291 };
292 llvm::StringMap<LookupFileCacheInfo, llvm::BumpPtrAllocator> LookupFileCache;
293
294 /// Collection mapping a framework or subframework
295 /// name like "Carbon" to the Carbon.framework directory.
296 llvm::StringMap<FrameworkCacheEntry, llvm::BumpPtrAllocator> FrameworkMap;
297
298 /// Maps include file names (including the quotes or
299 /// angle brackets) to other include file names. This is used to support the
300 /// include_alias pragma for Microsoft compatibility.
301 using IncludeAliasMap =
302 llvm::StringMap<std::string, llvm::BumpPtrAllocator>;
303 std::unique_ptr<IncludeAliasMap> IncludeAliases;
304
305 /// This is a mapping from FileEntry -> HeaderMap, uniquing headermaps.
306 std::vector<std::pair<const FileEntry *, std::unique_ptr<HeaderMap>>> HeaderMaps;
307
308 /// The mapping between modules and headers.
309 mutable ModuleMap ModMap;
310
311 /// Describes whether a given directory has a module map in it.
312 llvm::DenseMap<const DirectoryEntry *, bool> DirectoryHasModuleMap;
313
314 /// Set of module map files we've already loaded, and a flag indicating
315 /// whether they were valid or not.
316 llvm::DenseMap<const FileEntry *, bool> LoadedModuleMaps;
317
318 // A map of discovered headers with their associated include file name.
319 llvm::DenseMap<const FileEntry *, llvm::SmallString<64>> IncludeNames;
320
321 /// Uniqued set of framework names, which is used to track which
322 /// headers were included as framework headers.
323 llvm::StringSet<llvm::BumpPtrAllocator> FrameworkNames;
324
325 /// Entity used to resolve the identifier IDs of controlling
326 /// macros into IdentifierInfo pointers, and keep the identifire up to date,
327 /// as needed.
328 ExternalPreprocessorSource *ExternalLookup = nullptr;
329
330 /// Entity used to look up stored header file information.
331 ExternalHeaderFileInfoSource *ExternalSource = nullptr;
332
333public:
334 HeaderSearch(std::shared_ptr<HeaderSearchOptions> HSOpts,
335 SourceManager &SourceMgr, DiagnosticsEngine &Diags,
336 const LangOptions &LangOpts, const TargetInfo *Target);
337 HeaderSearch(const HeaderSearch &) = delete;
338 HeaderSearch &operator=(const HeaderSearch &) = delete;
339
340 /// Retrieve the header-search options with which this header search
341 /// was initialized.
342 HeaderSearchOptions &getHeaderSearchOpts() const { return *HSOpts; }
343
344 FileManager &getFileMgr() const { return FileMgr; }
345
346 DiagnosticsEngine &getDiags() const { return Diags; }
347
348 /// Interface for setting the file search paths.
349 void SetSearchPaths(std::vector<DirectoryLookup> dirs, unsigned angledDirIdx,
350 unsigned systemDirIdx, bool noCurDirSearch,
351 llvm::DenseMap<unsigned, unsigned> searchDirToHSEntry);
352
353 /// Add an additional search path.
354 void AddSearchPath(const DirectoryLookup &dir, bool isAngled);
355
356 /// Add an additional system search path.
357 void AddSystemSearchPath(const DirectoryLookup &dir) {
358 SearchDirs.push_back(dir);
359 SearchDirsUsage.push_back(false);
360 }
361
362 /// Set the list of system header prefixes.
363 void SetSystemHeaderPrefixes(ArrayRef<std::pair<std::string, bool>> P) {
364 SystemHeaderPrefixes.assign(P.begin(), P.end());
365 }
366
367 /// Checks whether the map exists or not.
368 bool HasIncludeAliasMap() const { return (bool)IncludeAliases; }
369
370 /// Map the source include name to the dest include name.
371 ///
372 /// The Source should include the angle brackets or quotes, the dest
373 /// should not. This allows for distinction between <> and "" headers.
374 void AddIncludeAlias(StringRef Source, StringRef Dest) {
375 if (!IncludeAliases)
376 IncludeAliases.reset(new IncludeAliasMap);
377 (*IncludeAliases)[Source] = std::string(Dest);
378 }
379
380 /// Maps one header file name to a different header
381 /// file name, for use with the include_alias pragma. Note that the source
382 /// file name should include the angle brackets or quotes. Returns StringRef
383 /// as null if the header cannot be mapped.
384 StringRef MapHeaderToIncludeAlias(StringRef Source) {
385 assert(IncludeAliases && "Trying to map headers when there's no map");
386
387 // Do any filename replacements before anything else
388 IncludeAliasMap::const_iterator Iter = IncludeAliases->find(Source);
389 if (Iter != IncludeAliases->end())
390 return Iter->second;
391 return {};
392 }
393
394 /// Set the hash to use for module cache paths.
395 void setModuleHash(StringRef Hash) { ModuleHash = std::string(Hash); }
396
397 /// Set the path to the module cache.
398 void setModuleCachePath(StringRef CachePath) {
399 ModuleCachePath = std::string(CachePath);
400 }
401
402 /// Retrieve the module hash.
403 StringRef getModuleHash() const { return ModuleHash; }
404
405 /// Retrieve the path to the module cache.
406 StringRef getModuleCachePath() const { return ModuleCachePath; }
407
408 /// Consider modules when including files from this directory.
409 void setDirectoryHasModuleMap(const DirectoryEntry* Dir) {
410 DirectoryHasModuleMap[Dir] = true;
411 }
412
413 /// Forget everything we know about headers so far.
414 void ClearFileInfo() {
415 FileInfo.clear();
416 }
417
418 void SetExternalLookup(ExternalPreprocessorSource *EPS) {
419 ExternalLookup = EPS;
420 }
421
422 ExternalPreprocessorSource *getExternalLookup() const {
423 return ExternalLookup;
424 }
425
426 /// Set the external source of header information.
427 void SetExternalSource(ExternalHeaderFileInfoSource *ES) {
428 ExternalSource = ES;
429 }
430
431 /// Set the target information for the header search, if not
432 /// already known.
433 void setTarget(const TargetInfo &Target);
434
435 /// Given a "foo" or \<foo> reference, look up the indicated file,
436 /// return null on failure.
437 ///
438 /// \returns If successful, this returns 'UsedDir', the DirectoryLookup member
439 /// the file was found in, or null if not applicable.
440 ///
441 /// \param IncludeLoc Used for diagnostics if valid.
442 ///
443 /// \param isAngled indicates whether the file reference is a <> reference.
444 ///
445 /// \param CurDir If non-null, the file was found in the specified directory
446 /// search location. This is used to implement \#include_next.
447 ///
448 /// \param Includers Indicates where the \#including file(s) are, in case
449 /// relative searches are needed. In reverse order of inclusion.
450 ///
451 /// \param SearchPath If non-null, will be set to the search path relative
452 /// to which the file was found. If the include path is absolute, SearchPath
453 /// will be set to an empty string.
454 ///
455 /// \param RelativePath If non-null, will be set to the path relative to
456 /// SearchPath at which the file was found. This only differs from the
457 /// Filename for framework includes.
458 ///
459 /// \param SuggestedModule If non-null, and the file found is semantically
460 /// part of a known module, this will be set to the module that should
461 /// be imported instead of preprocessing/parsing the file found.
462 ///
463 /// \param IsMapped If non-null, and the search involved header maps, set to
464 /// true.
465 ///
466 /// \param IsFrameworkFound If non-null, will be set to true if a framework is
467 /// found in any of searched SearchDirs. Will be set to false if a framework
468 /// is found only through header maps. Doesn't guarantee the requested file is
469 /// found.
470 Optional<FileEntryRef> LookupFile(
471 StringRef Filename, SourceLocation IncludeLoc, bool isAngled,
472 ConstSearchDirIterator FromDir, ConstSearchDirIterator *CurDir,
473 ArrayRef<std::pair<const FileEntry *, const DirectoryEntry *>> Includers,
474 SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
475 Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule,
476 bool *IsMapped, bool *IsFrameworkFound, bool SkipCache = false,
477 bool BuildSystemModule = false, bool OpenFile = true,
478 bool CacheFailures = true);
479
480 /// Look up a subframework for the specified \#include file.
481 ///
482 /// For example, if \#include'ing <HIToolbox/HIToolbox.h> from
483 /// within ".../Carbon.framework/Headers/Carbon.h", check to see if
484 /// HIToolbox is a subframework within Carbon.framework. If so, return
485 /// the FileEntry for the designated file, otherwise return null.
486 Optional<FileEntryRef> LookupSubframeworkHeader(
487 StringRef Filename, const FileEntry *ContextFileEnt,
488 SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
489 Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule);
490
491 /// Look up the specified framework name in our framework cache.
492 /// \returns The DirectoryEntry it is in if we know, null otherwise.
493 FrameworkCacheEntry &LookupFrameworkCache(StringRef FWName) {
494 return FrameworkMap[FWName];
495 }
496
497 /// Mark the specified file as a target of a \#include,
498 /// \#include_next, or \#import directive.
499 ///
500 /// \return false if \#including the file will have no effect or true
501 /// if we should include it.
502 bool ShouldEnterIncludeFile(Preprocessor &PP, const FileEntry *File,
503 bool isImport, bool ModulesEnabled, Module *M,
504 bool &IsFirstIncludeOfFile);
505
506 /// Return whether the specified file is a normal header,
507 /// a system header, or a C++ friendly system header.
508 SrcMgr::CharacteristicKind getFileDirFlavor(const FileEntry *File) {
509 return (SrcMgr::CharacteristicKind)getFileInfo(File).DirInfo;
510 }
511
512 /// Mark the specified file as a "once only" file due to
513 /// \#pragma once.
514 void MarkFileIncludeOnce(const FileEntry *File) {
515 HeaderFileInfo &FI = getFileInfo(File);
516 FI.isPragmaOnce = true;
517 }
518
519 /// Mark the specified file as a system header, e.g. due to
520 /// \#pragma GCC system_header.
521 void MarkFileSystemHeader(const FileEntry *File) {
522 getFileInfo(File).DirInfo = SrcMgr::C_System;
523 }
524
525 /// Mark the specified file as part of a module.
526 void MarkFileModuleHeader(const FileEntry *FE,
527 ModuleMap::ModuleHeaderRole Role,
528 bool isCompilingModuleHeader);
529
530 /// Mark the specified file as having a controlling macro.
531 ///
532 /// This is used by the multiple-include optimization to eliminate
533 /// no-op \#includes.
534 void SetFileControllingMacro(const FileEntry *File,
535 const IdentifierInfo *ControllingMacro) {
536 getFileInfo(File).ControllingMacro = ControllingMacro;
537 }
538
539 /// Determine whether this file is intended to be safe from
540 /// multiple inclusions, e.g., it has \#pragma once or a controlling
541 /// macro.
542 ///
543 /// This routine does not consider the effect of \#import
544 bool isFileMultipleIncludeGuarded(const FileEntry *File);
545
546 /// Determine whether the given file is known to have ever been \#imported.
547 bool hasFileBeenImported(const FileEntry *File) {
548 const HeaderFileInfo *FI = getExistingFileInfo(File);
549 return FI && FI->isImport;
550 }
551
552 /// Determine which HeaderSearchOptions::UserEntries have been successfully
553 /// used so far and mark their index with 'true' in the resulting bit vector.
554 /// Note: implicit module maps don't contribute to entry usage.
555 std::vector<bool> computeUserEntryUsage() const;
556
557 /// This method returns a HeaderMap for the specified
558 /// FileEntry, uniquing them through the 'HeaderMaps' datastructure.
559 const HeaderMap *CreateHeaderMap(const FileEntry *FE);
560
561 /// Get filenames for all registered header maps.
562 void getHeaderMapFileNames(SmallVectorImpl<std::string> &Names) const;
563
564 /// Retrieve the name of the cached module file that should be used
565 /// to load the given module.
566 ///
567 /// \param Module The module whose module file name will be returned.
568 ///
569 /// \returns The name of the module file that corresponds to this module,
570 /// or an empty string if this module does not correspond to any module file.
571 std::string getCachedModuleFileName(Module *Module);
572
573 /// Retrieve the name of the prebuilt module file that should be used
574 /// to load a module with the given name.
575 ///
576 /// \param ModuleName The module whose module file name will be returned.
577 ///
578 /// \param FileMapOnly If true, then only look in the explicit module name
579 // to file name map and skip the directory search.
580 ///
581 /// \returns The name of the module file that corresponds to this module,
582 /// or an empty string if this module does not correspond to any module file.
583 std::string getPrebuiltModuleFileName(StringRef ModuleName,
584 bool FileMapOnly = false);
585
586 /// Retrieve the name of the prebuilt module file that should be used
587 /// to load the given module.
588 ///
589 /// \param Module The module whose module file name will be returned.
590 ///
591 /// \returns The name of the module file that corresponds to this module,
592 /// or an empty string if this module does not correspond to any module file.
593 std::string getPrebuiltImplicitModuleFileName(Module *Module);
594
595 /// Retrieve the name of the (to-be-)cached module file that should
596 /// be used to load a module with the given name.
597 ///
598 /// \param ModuleName The module whose module file name will be returned.
599 ///
600 /// \param ModuleMapPath A path that when combined with \c ModuleName
601 /// uniquely identifies this module. See Module::ModuleMap.
602 ///
603 /// \returns The name of the module file that corresponds to this module,
604 /// or an empty string if this module does not correspond to any module file.
605 std::string getCachedModuleFileName(StringRef ModuleName,
606 StringRef ModuleMapPath);
607
608 /// Lookup a module Search for a module with the given name.
609 ///
610 /// \param ModuleName The name of the module we're looking for.
611 ///
612 /// \param ImportLoc Location of the module include/import.
613 ///
614 /// \param AllowSearch Whether we are allowed to search in the various
615 /// search directories to produce a module definition. If not, this lookup
616 /// will only return an already-known module.
617 ///
618 /// \param AllowExtraModuleMapSearch Whether we allow to search modulemaps
619 /// in subdirectories.
620 ///
621 /// \returns The module with the given name.
622 Module *lookupModule(StringRef ModuleName,
623 SourceLocation ImportLoc = SourceLocation(),
624 bool AllowSearch = true,
625 bool AllowExtraModuleMapSearch = false);
626
627 /// Try to find a module map file in the given directory, returning
628 /// \c nullptr if none is found.
629 const FileEntry *lookupModuleMapFile(const DirectoryEntry *Dir,
630 bool IsFramework);
631
632 /// Determine whether there is a module map that may map the header
633 /// with the given file name to a (sub)module.
634 /// Always returns false if modules are disabled.
635 ///
636 /// \param Filename The name of the file.
637 ///
638 /// \param Root The "root" directory, at which we should stop looking for
639 /// module maps.
640 ///
641 /// \param IsSystem Whether the directories we're looking at are system
642 /// header directories.
643 bool hasModuleMap(StringRef Filename, const DirectoryEntry *Root,
644 bool IsSystem);
645
646 /// Retrieve the module that corresponds to the given file, if any.
647 ///
648 /// \param File The header that we wish to map to a module.
649 /// \param AllowTextual Whether we want to find textual headers too.
650 ModuleMap::KnownHeader findModuleForHeader(const FileEntry *File,
651 bool AllowTextual = false) const;
652
653 /// Retrieve all the modules corresponding to the given file.
654 ///
655 /// \ref findModuleForHeader should typically be used instead of this.
656 ArrayRef<ModuleMap::KnownHeader>
657 findAllModulesForHeader(const FileEntry *File) const;
658
659 /// Read the contents of the given module map file.
660 ///
661 /// \param File The module map file.
662 /// \param IsSystem Whether this file is in a system header directory.
663 /// \param ID If the module map file is already mapped (perhaps as part of
664 /// processing a preprocessed module), the ID of the file.
665 /// \param Offset [inout] An offset within ID to start parsing. On exit,
666 /// filled by the end of the parsed contents (either EOF or the
667 /// location of an end-of-module-map pragma).
668 /// \param OriginalModuleMapFile The original path to the module map file,
669 /// used to resolve paths within the module (this is required when
670 /// building the module from preprocessed source).
671 /// \returns true if an error occurred, false otherwise.
672 bool loadModuleMapFile(const FileEntry *File, bool IsSystem,
673 FileID ID = FileID(), unsigned *Offset = nullptr,
674 StringRef OriginalModuleMapFile = StringRef());
675
676 /// Collect the set of all known, top-level modules.
677 ///
678 /// \param Modules Will be filled with the set of known, top-level modules.
679 void collectAllModules(SmallVectorImpl<Module *> &Modules);
680
681 /// Load all known, top-level system modules.
682 void loadTopLevelSystemModules();
683
684private:
685 /// Lookup a module with the given module name and search-name.
686 ///
687 /// \param ModuleName The name of the module we're looking for.
688 ///
689 /// \param SearchName The "search-name" to derive filesystem paths from
690 /// when looking for the module map; this is usually equal to ModuleName,
691 /// but for compatibility with some buggy frameworks, additional attempts
692 /// may be made to find the module under a related-but-different search-name.
693 ///
694 /// \param ImportLoc Location of the module include/import.
695 ///
696 /// \param AllowExtraModuleMapSearch Whether we allow to search modulemaps
697 /// in subdirectories.
698 ///
699 /// \returns The module named ModuleName.
700 Module *lookupModule(StringRef ModuleName, StringRef SearchName,
701 SourceLocation ImportLoc,
702 bool AllowExtraModuleMapSearch = false);
703
704 /// Retrieve the name of the (to-be-)cached module file that should
705 /// be used to load a module with the given name.
706 ///
707 /// \param ModuleName The module whose module file name will be returned.
708 ///
709 /// \param ModuleMapPath A path that when combined with \c ModuleName
710 /// uniquely identifies this module. See Module::ModuleMap.
711 ///
712 /// \param CachePath A path to the module cache.
713 ///
714 /// \returns The name of the module file that corresponds to this module,
715 /// or an empty string if this module does not correspond to any module file.
716 std::string getCachedModuleFileNameImpl(StringRef ModuleName,
717 StringRef ModuleMapPath,
718 StringRef CachePath);
719
720 /// Retrieve a module with the given name, which may be part of the
721 /// given framework.
722 ///
723 /// \param Name The name of the module to retrieve.
724 ///
725 /// \param Dir The framework directory (e.g., ModuleName.framework).
726 ///
727 /// \param IsSystem Whether the framework directory is part of the system
728 /// frameworks.
729 ///
730 /// \returns The module, if found; otherwise, null.
731 Module *loadFrameworkModule(StringRef Name, DirectoryEntryRef Dir,
732 bool IsSystem);
733
734 /// Load all of the module maps within the immediate subdirectories
735 /// of the given search directory.
736 void loadSubdirectoryModuleMaps(DirectoryLookup &SearchDir);
737
738 /// Find and suggest a usable module for the given file.
739 ///
740 /// \return \c true if the file can be used, \c false if we are not permitted to
741 /// find this file due to requirements from \p RequestingModule.
742 bool findUsableModuleForHeader(const FileEntry *File,
743 const DirectoryEntry *Root,
744 Module *RequestingModule,
745 ModuleMap::KnownHeader *SuggestedModule,
746 bool IsSystemHeaderDir);
747
748 /// Find and suggest a usable module for the given file, which is part of
749 /// the specified framework.
750 ///
751 /// \return \c true if the file can be used, \c false if we are not permitted to
752 /// find this file due to requirements from \p RequestingModule.
753 bool findUsableModuleForFrameworkHeader(
754 const FileEntry *File, StringRef FrameworkName, Module *RequestingModule,
755 ModuleMap::KnownHeader *SuggestedModule, bool IsSystemFramework);
756
757 /// Look up the file with the specified name and determine its owning
758 /// module.
759 Optional<FileEntryRef>
760 getFileAndSuggestModule(StringRef FileName, SourceLocation IncludeLoc,
761 const DirectoryEntry *Dir, bool IsSystemHeaderDir,
762 Module *RequestingModule,
763 ModuleMap::KnownHeader *SuggestedModule,
764 bool OpenFile = true, bool CacheFailures = true);
765
766 /// Cache the result of a successful lookup at the given include location
767 /// using the search path at \c HitIt.
768 void cacheLookupSuccess(LookupFileCacheInfo &CacheLookup,
769 ConstSearchDirIterator HitIt,
770 SourceLocation IncludeLoc);
771
772 /// Note that a lookup at the given include location was successful using the
773 /// search path at index `HitIdx`.
774 void noteLookupUsage(unsigned HitIdx, SourceLocation IncludeLoc);
775
776public:
777 /// Retrieve the module map.
778 ModuleMap &getModuleMap() { return ModMap; }
779
780 /// Retrieve the module map.
781 const ModuleMap &getModuleMap() const { return ModMap; }
782
783 unsigned header_file_size() const { return FileInfo.size(); }
784
785 /// Return the HeaderFileInfo structure for the specified FileEntry,
786 /// in preparation for updating it in some way.
787 HeaderFileInfo &getFileInfo(const FileEntry *FE);
788
789 /// Return the HeaderFileInfo structure for the specified FileEntry,
790 /// if it has ever been filled in.
791 /// \param WantExternal Whether the caller wants purely-external header file
792 /// info (where \p External is true).
793 const HeaderFileInfo *getExistingFileInfo(const FileEntry *FE,
794 bool WantExternal = true) const;
795
796 SearchDirIterator search_dir_begin() { return {*this, 0}; }
797 SearchDirIterator search_dir_end() { return {*this, SearchDirs.size()}; }
798 SearchDirRange search_dir_range() {
799 return {search_dir_begin(), search_dir_end()};
800 }
801
802 ConstSearchDirIterator search_dir_begin() const { return quoted_dir_begin(); }
803 ConstSearchDirIterator search_dir_end() const { return system_dir_end(); }
804 ConstSearchDirRange search_dir_range() const {
805 return {search_dir_begin(), search_dir_end()};
806 }
807
808 unsigned search_dir_size() const { return SearchDirs.size(); }
809
810 ConstSearchDirIterator quoted_dir_begin() const { return {*this, 0}; }
811 ConstSearchDirIterator quoted_dir_end() const { return angled_dir_begin(); }
812
813 ConstSearchDirIterator angled_dir_begin() const {
814 return {*this, AngledDirIdx};
815 }
816 ConstSearchDirIterator angled_dir_end() const { return system_dir_begin(); }
817
818 ConstSearchDirIterator system_dir_begin() const {
819 return {*this, SystemDirIdx};
820 }
821 ConstSearchDirIterator system_dir_end() const {
822 return {*this, SearchDirs.size()};
823 }
824
825 /// Get the index of the given search directory.
826 unsigned searchDirIdx(const DirectoryLookup &DL) const;
827
828 /// Retrieve a uniqued framework name.
829 StringRef getUniqueFrameworkName(StringRef Framework);
830
831 /// Retrieve the include name for the header.
832 ///
833 /// \param File The entry for a given header.
834 /// \returns The name of how the file was included when the header's location
835 /// was resolved.
836 StringRef getIncludeNameForHeader(const FileEntry *File) const;
837
838 /// Suggest a path by which the specified file could be found, for use in
839 /// diagnostics to suggest a #include. Returned path will only contain forward
840 /// slashes as separators. MainFile is the absolute path of the file that we
841 /// are generating the diagnostics for. It will try to shorten the path using
842 /// MainFile location, if none of the include search directories were prefix
843 /// of File.
844 ///
845 /// \param IsSystem If non-null, filled in to indicate whether the suggested
846 /// path is relative to a system header directory.
847 std::string suggestPathToFileForDiagnostics(const FileEntry *File,
848 llvm::StringRef MainFile,
849 bool *IsSystem = nullptr);
850
851 /// Suggest a path by which the specified file could be found, for use in
852 /// diagnostics to suggest a #include. Returned path will only contain forward
853 /// slashes as separators. MainFile is the absolute path of the file that we
854 /// are generating the diagnostics for. It will try to shorten the path using
855 /// MainFile location, if none of the include search directories were prefix
856 /// of File.
857 ///
858 /// \param WorkingDir If non-empty, this will be prepended to search directory
859 /// paths that are relative.
860 std::string suggestPathToFileForDiagnostics(llvm::StringRef File,
861 llvm::StringRef WorkingDir,
862 llvm::StringRef MainFile,
863 bool *IsSystem = nullptr);
864
865 void PrintStats();
866
867 size_t getTotalMemory() const;
868
869private:
870 /// Describes what happened when we tried to load a module map file.
871 enum LoadModuleMapResult {
872 /// The module map file had already been loaded.
873 LMM_AlreadyLoaded,
874
875 /// The module map file was loaded by this invocation.
876 LMM_NewlyLoaded,
877
878 /// There is was directory with the given name.
879 LMM_NoDirectory,
880
881 /// There was either no module map file or the module map file was
882 /// invalid.
883 LMM_InvalidModuleMap
884 };
885
886 LoadModuleMapResult loadModuleMapFileImpl(const FileEntry *File,
887 bool IsSystem,
888 DirectoryEntryRef Dir,
889 FileID ID = FileID(),
890 unsigned *Offset = nullptr);
891
892 /// Try to load the module map file in the given directory.
893 ///
894 /// \param DirName The name of the directory where we will look for a module
895 /// map file.
896 /// \param IsSystem Whether this is a system header directory.
897 /// \param IsFramework Whether this is a framework directory.
898 ///
899 /// \returns The result of attempting to load the module map file from the
900 /// named directory.
901 LoadModuleMapResult loadModuleMapFile(StringRef DirName, bool IsSystem,
902 bool IsFramework);
903
904 /// Try to load the module map file in the given directory.
905 ///
906 /// \param Dir The directory where we will look for a module map file.
907 /// \param IsSystem Whether this is a system header directory.
908 /// \param IsFramework Whether this is a framework directory.
909 ///
910 /// \returns The result of attempting to load the module map file from the
911 /// named directory.
912 LoadModuleMapResult loadModuleMapFile(DirectoryEntryRef Dir, bool IsSystem,
913 bool IsFramework);
914};
915
916/// Apply the header search options to get given HeaderSearch object.
917void ApplyHeaderSearchOptions(HeaderSearch &HS,
918 const HeaderSearchOptions &HSOpts,
919 const LangOptions &Lang,
920 const llvm::Triple &triple);
921
922} // namespace clang
923
924#endif // LLVM_CLANG_LEX_HEADERSEARCH_H
925

Warning: This file is not a C or C++ file. It does not have highlighting.

source code of clang/include/clang/Lex/HeaderSearch.h