clang-tools  14.0.0git
Headers.h
Go to the documentation of this file.
1 //===--- Headers.h - Include headers -----------------------------*- 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 #ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_HEADERS_H
10 #define LLVM_CLANG_TOOLS_EXTRA_CLANGD_HEADERS_H
11 
12 #include "Protocol.h"
13 #include "SourceCode.h"
14 #include "index/Symbol.h"
15 #include "support/Path.h"
16 #include "clang/Basic/TokenKinds.h"
17 #include "clang/Format/Format.h"
18 #include "clang/Lex/HeaderSearch.h"
19 #include "clang/Lex/PPCallbacks.h"
20 #include "clang/Tooling/Inclusions/HeaderIncludes.h"
21 #include "llvm/ADT/ArrayRef.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/ADT/StringSet.h"
24 #include "llvm/Support/Error.h"
25 #include "llvm/Support/VirtualFileSystem.h"
26 #include <string>
27 
28 namespace clang {
29 namespace clangd {
30 
31 /// Returns true if \p Include is literal include like "path" or <path>.
32 bool isLiteralInclude(llvm::StringRef Include);
33 
34 /// Represents a header file to be #include'd.
35 struct HeaderFile {
36  std::string File;
37  /// If this is true, `File` is a literal string quoted with <> or "" that
38  /// can be #included directly; otherwise, `File` is an absolute file path.
39  bool Verbatim;
40 
41  bool valid() const;
42 };
43 
44 /// Creates a `HeaderFile` from \p Header which can be either a URI or a literal
45 /// include.
46 llvm::Expected<HeaderFile> toHeaderFile(llvm::StringRef Header,
47  llvm::StringRef HintPath);
48 
49 // Returns include headers for \p Sym sorted by popularity. If two headers are
50 // equally popular, prefer the shorter one.
51 llvm::SmallVector<llvm::StringRef, 1> getRankedIncludes(const Symbol &Sym);
52 
53 // An #include directive that we found in the main file.
54 struct Inclusion {
55  tok::PPKeywordKind Directive; // Directive used for inclusion, e.g. import
56  std::string Written; // Inclusion name as written e.g. <vector>.
57  Path Resolved; // Resolved path of included file. Empty if not resolved.
58  unsigned HashOffset = 0; // Byte offset from start of file to #.
59  int HashLine = 0; // Line number containing the directive, 0-indexed.
60  SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
61 };
62 llvm::raw_ostream &operator<<(llvm::raw_ostream &, const Inclusion &);
63 bool operator==(const Inclusion &LHS, const Inclusion &RHS);
64 
65 // Contains information about one file in the build grpah and its direct
66 // dependencies. Doesn't own the strings it references (IncludeGraph is
67 // self-contained).
69  enum class SourceFlag : uint8_t {
70  None = 0,
71  // Whether current file is a main file rather than a header.
72  IsTU = 1 << 0,
73  // Whether current file had any uncompilable errors during indexing.
74  HadErrors = 1 << 1,
75  };
76 
78  llvm::StringRef URI;
80  std::vector<llvm::StringRef> DirectIncludes;
81 };
82 // FileURI and FileInclusions are references to keys of the map containing
83 // them.
84 // Important: The graph generated by those callbacks might contain cycles, self
85 // edges and multi edges.
86 using IncludeGraph = llvm::StringMap<IncludeGraphNode>;
87 
90  return static_cast<IncludeGraphNode::SourceFlag>(static_cast<uint8_t>(A) |
91  static_cast<uint8_t>(B));
92 }
93 
96  return static_cast<uint8_t>(A) & static_cast<uint8_t>(B);
97 }
98 
101  return A = A | B;
102 }
103 
104 // Information captured about the inclusion graph in a translation unit.
105 // This includes detailed information about the direct #includes, and summary
106 // information about all transitive includes.
107 //
108 // It should be built incrementally with collectIncludeStructureCallback().
109 // When we build the preamble, we capture and store its include structure along
110 // with the preamble data. When we use the preamble, we can copy its
111 // IncludeStructure and use another collectIncludeStructureCallback() to fill
112 // in any non-preamble inclusions.
114 public:
115  std::vector<Inclusion> MainFileIncludes;
116 
117  // Return all transitively reachable files.
118  llvm::ArrayRef<std::string> allHeaders() const { return RealPathNames; }
119 
120  // Return all transitively reachable files, and their minimum include depth.
121  // All transitive includes (absolute paths), with their minimum include depth.
122  // Root --> 0, #included file --> 1, etc.
123  // Root is clang's name for a file, which may not be absolute.
124  // Usually it should be SM.getFileEntryForID(SM.getMainFileID())->getName().
125  llvm::StringMap<unsigned> includeDepth(llvm::StringRef Root) const;
126 
127  // This updates IncludeDepth(), but not MainFileIncludes.
128  void recordInclude(llvm::StringRef IncludingName,
129  llvm::StringRef IncludedName,
130  llvm::StringRef IncludedRealName);
131 
132 private:
133  // Identifying files in a way that persists from preamble build to subsequent
134  // builds is surprisingly hard. FileID is unavailable in InclusionDirective(),
135  // and RealPathName and UniqueID are not preserved in the preamble.
136  // We use the FileEntry::Name, which is stable, interned into a "file index".
137  // The paths we want to expose are the RealPathName, so store those too.
138  std::vector<std::string> RealPathNames; // In file index order.
139  unsigned fileIndex(llvm::StringRef Name);
140  llvm::StringMap<unsigned> NameToIndex; // Values are file indexes.
141  // Maps a file's index to that of the files it includes.
142  llvm::DenseMap<unsigned, llvm::SmallVector<unsigned>> IncludeChildren;
143 };
144 
145 /// Returns a PPCallback that visits all inclusions in the main file.
146 std::unique_ptr<PPCallbacks>
147 collectIncludeStructureCallback(const SourceManager &SM, IncludeStructure *Out);
148 
149 // Calculates insertion edit for including a new header in a file.
151 public:
152  // If \p HeaderSearchInfo is nullptr (e.g. when compile command is
153  // infeasible), this will only try to insert verbatim headers, and
154  // include path of non-verbatim header will not be shortened.
155  IncludeInserter(StringRef FileName, StringRef Code,
156  const format::FormatStyle &Style, StringRef BuildDir,
157  HeaderSearch *HeaderSearchInfo)
158  : FileName(FileName), Code(Code), BuildDir(BuildDir),
159  HeaderSearchInfo(HeaderSearchInfo),
160  Inserter(FileName, Code, Style.IncludeStyle) {}
161 
162  void addExisting(const Inclusion &Inc);
163 
164  /// Checks whether to add an #include of the header into \p File.
165  /// An #include will not be added if:
166  /// - Either \p DeclaringHeader or \p InsertedHeader is already (directly)
167  /// in \p Inclusions (including those included via different paths).
168  /// - \p DeclaringHeader or \p InsertedHeader is the same as \p File.
169  ///
170  /// \param DeclaringHeader is path of the original header corresponding to \p
171  /// InsertedHeader e.g. the header that declares a symbol.
172  /// \param InsertedHeader The preferred header to be inserted. This could be
173  /// the same as DeclaringHeader but must be provided.
174  bool shouldInsertInclude(PathRef DeclaringHeader,
175  const HeaderFile &InsertedHeader) const;
176 
177  /// Determines the preferred way to #include a file, taking into account the
178  /// search path. Usually this will prefer a shorter representation like
179  /// 'Foo/Bar.h' over a longer one like 'Baz/include/Foo/Bar.h'.
180  ///
181  /// \param InsertedHeader The preferred header to be inserted.
182  ///
183  /// \param IncludingFile is the absolute path of the file that InsertedHeader
184  /// will be inserted.
185  ///
186  /// \return A quoted "path" or <path> to be included, or None if it couldn't
187  /// be shortened.
188  llvm::Optional<std::string>
189  calculateIncludePath(const HeaderFile &InsertedHeader,
190  llvm::StringRef IncludingFile) const;
191 
192  /// Calculates an edit that inserts \p VerbatimHeader into code. If the header
193  /// is already included, this returns None.
194  llvm::Optional<TextEdit> insert(llvm::StringRef VerbatimHeader) const;
195 
196 private:
197  StringRef FileName;
198  StringRef Code;
199  StringRef BuildDir;
200  HeaderSearch *HeaderSearchInfo = nullptr;
201  llvm::StringSet<> IncludedHeaders; // Both written and resolved.
202  tooling::HeaderIncludes Inserter; // Computers insertion replacement.
203 };
204 
205 } // namespace clangd
206 } // namespace clang
207 
208 #endif // LLVM_CLANG_TOOLS_EXTRA_CLANGD_HEADERS_H
clang::clangd::HeaderFile
Represents a header file to be #include'd.
Definition: Headers.h:35
clang::clangd::IncludeInserter::IncludeInserter
IncludeInserter(StringRef FileName, StringRef Code, const format::FormatStyle &Style, StringRef BuildDir, HeaderSearch *HeaderSearchInfo)
Definition: Headers.h:155
clang::clangd::Path
std::string Path
A typedef to represent a file path.
Definition: Path.h:26
Path.h
FormatStyle
static cl::opt< std::string > FormatStyle("format-style", cl::desc(R"( Style for formatting code around applied fixes: - 'none' (default) turns off formatting - 'file' (literally 'file', not a placeholder) uses .clang-format file in the closest parent directory - '{ <json> }' specifies options inline, e.g. -format-style='{BasedOnStyle: llvm, IndentWidth: 8}' - 'llvm', 'google', 'webkit', 'mozilla' See clang-format documentation for the up-to-date information about formatting styles and options. This option overrides the 'FormatStyle` option in .clang-tidy file, if any. )"), cl::init("none"), cl::cat(ClangTidyCategory))
clang::clangd::IncludeGraphNode::Digest
FileDigest Digest
Definition: Headers.h:79
Root
ASTNode Root
Definition: DumpAST.cpp:332
clang::clangd::HeaderFile::valid
bool valid() const
Definition: Headers.cpp:111
clang::clangd::IncludeGraphNode::SourceFlag::IsTU
@ IsTU
clang::clangd::IncludeInserter::calculateIncludePath
llvm::Optional< std::string > calculateIncludePath(const HeaderFile &InsertedHeader, llvm::StringRef IncludingFile) const
Determines the preferred way to #include a file, taking into account the search path.
Definition: Headers.cpp:229
clang::clangd::IncludeGraphNode::SourceFlag::None
@ None
clang::clangd::IncludeStructure::MainFileIncludes
std::vector< Inclusion > MainFileIncludes
Definition: Headers.h:115
clang::clangd::operator&
DeclRelationSet operator&(DeclRelation L, DeclRelation R)
Definition: FindTarget.h:214
clang::clangd::IncludeInserter::shouldInsertInclude
bool shouldInsertInclude(PathRef DeclaringHeader, const HeaderFile &InsertedHeader) const
Checks whether to add an #include of the header into File.
Definition: Headers.cpp:215
Protocol.h
clang::clangd::IncludeStructure
Definition: Headers.h:113
clang::clangd::getRankedIncludes
llvm::SmallVector< llvm::StringRef, 1 > getRankedIncludes(const Symbol &Sym)
Definition: Headers.cpp:136
ns1::ns2::A
@ A
Definition: CategoricalFeature.h:3
Code
std::string Code
Definition: FindTargetTests.cpp:67
clang::clangd::Inclusion::Directive
tok::PPKeywordKind Directive
Definition: Headers.h:55
clang::clangd::Inclusion::HashLine
int HashLine
Definition: Headers.h:59
clang::clangd::operator|=
IncludeGraphNode::SourceFlag & operator|=(IncludeGraphNode::SourceFlag &A, IncludeGraphNode::SourceFlag B)
Definition: Headers.h:100
clang::clangd::Inclusion::Written
std::string Written
Definition: Headers.h:56
clang::clangd::Symbol
The class presents a C++ symbol, e.g.
Definition: Symbol.h:36
clang::clangd::IncludeGraphNode::SourceFlag
SourceFlag
Definition: Headers.h:69
Name
static constexpr llvm::StringLiteral Name
Definition: UppercaseLiteralSuffixCheck.cpp:27
clang::clangd::IncludeGraphNode::DirectIncludes
std::vector< llvm::StringRef > DirectIncludes
Definition: Headers.h:80
clang::clangd::collectIncludeStructureCallback
std::unique_ptr< PPCallbacks > collectIncludeStructureCallback(const SourceManager &SM, IncludeStructure *Out)
Returns a PPCallback that visits all inclusions in the main file.
Definition: Headers.cpp:152
FileName
StringRef FileName
Definition: KernelNameRestrictionCheck.cpp:46
clang::clangd::IncludeGraphNode::Flags
SourceFlag Flags
Definition: Headers.h:77
clang::clangd::toHeaderFile
llvm::Expected< HeaderFile > toHeaderFile(llvm::StringRef Header, llvm::StringRef HintPath)
Creates a HeaderFile from Header which can be either a URI or a literal include.
Definition: Headers.cpp:116
clang::clangd::operator<<
llvm::raw_ostream & operator<<(llvm::raw_ostream &OS, const CodeCompletion &C)
Definition: CodeComplete.cpp:2013
Symbol.h
SourceCode.h
clang::clangd::Inclusion
Definition: Headers.h:54
clang::clangd::isLiteralInclude
bool isLiteralInclude(llvm::StringRef Include)
Returns true if Include is literal include like "path" or <path>.
Definition: Headers.cpp:107
clang::clangd::IncludeGraphNode::SourceFlag::HadErrors
@ HadErrors
clang::clangd::IncludeInserter::addExisting
void addExisting(const Inclusion &Inc)
Definition: Headers.cpp:207
clang::clangd::PathRef
llvm::StringRef PathRef
A typedef to represent a ref to file path.
Definition: Path.h:29
clang::clangd::Inclusion::Resolved
Path Resolved
Definition: Headers.h:57
clang::clangd::IncludeGraphNode::URI
llvm::StringRef URI
Definition: Headers.h:78
clang::clangd::IncludeInserter::insert
llvm::Optional< TextEdit > insert(llvm::StringRef VerbatimHeader) const
Calculates an edit that inserts VerbatimHeader into code.
Definition: Headers.cpp:259
clang::clangd::Inclusion::FileKind
SrcMgr::CharacteristicKind FileKind
Definition: Headers.h:60
clang::clangd::FileDigest
std::array< uint8_t, 8 > FileDigest
Definition: SourceCode.h:40
clang::clangd::operator|
DeclRelationSet operator|(DeclRelation L, DeclRelation R)
Definition: FindTarget.h:211
clang::clangd::IncludeStructure::allHeaders
llvm::ArrayRef< std::string > allHeaders() const
Definition: Headers.h:118
clang
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
Definition: ApplyReplacements.h:27
clang::clangd::IncludeGraphNode
Definition: Headers.h:68
clang::clangd::IncludeStructure::includeDepth
llvm::StringMap< unsigned > includeDepth(llvm::StringRef Root) const
Definition: Headers.cpp:175
clang::clangd::Inclusion::HashOffset
unsigned HashOffset
Definition: Headers.h:58
clang::clangd::IncludeGraph
llvm::StringMap< IncludeGraphNode > IncludeGraph
Definition: Headers.h:86
clang::clangd::operator==
bool operator==(const Inclusion &LHS, const Inclusion &RHS)
Definition: Headers.cpp:273
clang::clangd::IncludeStructure::recordInclude
void recordInclude(llvm::StringRef IncludingName, llvm::StringRef IncludedName, llvm::StringRef IncludedRealName)
Definition: Headers.cpp:157
ns1::ns2::B
@ B
Definition: CategoricalFeature.h:3
Out
CompiledFragmentImpl & Out
Definition: ConfigCompile.cpp:100
clang::clangd::HeaderFile::File
std::string File
Definition: Headers.h:36
clang::clangd::IncludeInserter
Definition: Headers.h:150
clang::clangd::HeaderFile::Verbatim
bool Verbatim
If this is true, File is a literal string quoted with <> or "" that can be #included directly; otherw...
Definition: Headers.h:39