clang-tools 10.0.0

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