blob: 164a2005ac91f9bf76f64d1dce8d0353760b6047 [file] [log] [blame]
Eric Liuc5105f92018-02-16 14:15:55 +00001//===--- Headers.h - Include headers -----------------------------*- C++-*-===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Eric Liuc5105f92018-02-16 14:15:55 +00006//
7//===----------------------------------------------------------------------===//
8
9#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_HEADERS_H
10#define LLVM_CLANG_TOOLS_EXTRA_CLANGD_HEADERS_H
11
Eric Liu155f5a42018-05-14 12:19:16 +000012#include "Protocol.h"
Eric Liu63f419a2018-05-15 15:29:32 +000013#include "SourceCode.h"
Dmitri Gribenko08b49b52019-02-28 13:23:03 +000014#include "index/Symbol.h"
Sam McCallad97ccf2020-04-28 17:49:17 +020015#include "support/Path.h"
Kadir Cetinkaya6e017182020-04-15 22:00:19 +020016#include "clang/Basic/TokenKinds.h"
Eric Liu63f419a2018-05-15 15:29:32 +000017#include "clang/Format/Format.h"
18#include "clang/Lex/HeaderSearch.h"
Eric Liu155f5a42018-05-14 12:19:16 +000019#include "clang/Lex/PPCallbacks.h"
Eric Liu528eb652018-06-04 09:04:28 +000020#include "clang/Tooling/Inclusions/HeaderIncludes.h"
Eric Liudd662772019-01-28 14:01:55 +000021#include "llvm/ADT/ArrayRef.h"
Eric Liuc5105f92018-02-16 14:15:55 +000022#include "llvm/ADT/StringRef.h"
Eric Liu63f419a2018-05-15 15:29:32 +000023#include "llvm/ADT/StringSet.h"
Eric Liuc5105f92018-02-16 14:15:55 +000024#include "llvm/Support/Error.h"
Jonas Devliegherefc514902018-10-10 13:27:25 +000025#include "llvm/Support/VirtualFileSystem.h"
Kadir Cetinkaya6e017182020-04-15 22:00:19 +020026#include <string>
Eric Liuc5105f92018-02-16 14:15:55 +000027
28namespace clang {
29namespace clangd {
Eric Liu709bde82018-02-19 18:48:44 +000030
Eric Liu6c8e8582018-02-26 08:32:13 +000031/// Returns true if \p Include is literal include like "path" or <path>.
32bool isLiteralInclude(llvm::StringRef Include);
33
34/// Represents a header file to be #include'd.
35struct 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
Eric Liudd662772019-01-28 14:01:55 +000044/// Creates a `HeaderFile` from \p Header which can be either a URI or a literal
45/// include.
46llvm::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.
51llvm::SmallVector<llvm::StringRef, 1> getRankedIncludes(const Symbol &Sym);
52
Eric Liu155f5a42018-05-14 12:19:16 +000053// An #include directive that we found in the main file.
54struct Inclusion {
Kadir Cetinkaya6e017182020-04-15 22:00:19 +020055 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.
Sam McCall991e3162018-11-20 10:58:48 +000058 unsigned HashOffset = 0; // Byte offset from start of file to #.
Kadir Cetinkayad8700162020-05-04 10:48:19 +020059 int HashLine = 0; // Line number containing the directive, 0-indexed.
Sam McCall991e3162018-11-20 10:58:48 +000060 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
Eric Liu155f5a42018-05-14 12:19:16 +000061};
Kadir Cetinkaya53995522018-11-30 16:59:00 +000062llvm::raw_ostream &operator<<(llvm::raw_ostream &, const Inclusion &);
Kadir Cetinkaya717bef62020-04-23 17:44:51 +020063bool operator==(const Inclusion &LHS, const Inclusion &RHS);
Eric Liu155f5a42018-05-14 12:19:16 +000064
Kadir Cetinkayad08eab42018-11-27 16:08:53 +000065// 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).
68struct IncludeGraphNode {
Kadir Cetinkayaadbb3472019-07-04 09:52:04 +000069 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
77 SourceFlag Flags = SourceFlag::None;
Kadir Cetinkayad08eab42018-11-27 16:08:53 +000078 llvm::StringRef URI;
Simon Pilgrim2d12d812018-12-04 14:07:29 +000079 FileDigest Digest{{0}};
Kadir Cetinkayad08eab42018-11-27 16:08:53 +000080 std::vector<llvm::StringRef> DirectIncludes;
81};
82// FileURI and FileInclusions are references to keys of the map containing
83// them.
Kadir Cetinkaya53995522018-11-30 16:59:00 +000084// Important: The graph generated by those callbacks might contain cycles, self
85// edges and multi edges.
Kadir Cetinkayad08eab42018-11-27 16:08:53 +000086using IncludeGraph = llvm::StringMap<IncludeGraphNode>;
87
Kadir Cetinkayaadbb3472019-07-04 09:52:04 +000088inline IncludeGraphNode::SourceFlag operator|(IncludeGraphNode::SourceFlag A,
89 IncludeGraphNode::SourceFlag B) {
90 return static_cast<IncludeGraphNode::SourceFlag>(static_cast<uint8_t>(A) |
91 static_cast<uint8_t>(B));
92}
93
94inline bool operator&(IncludeGraphNode::SourceFlag A,
95 IncludeGraphNode::SourceFlag B) {
96 return static_cast<uint8_t>(A) & static_cast<uint8_t>(B);
97}
98
99inline IncludeGraphNode::SourceFlag &
100operator|=(IncludeGraphNode::SourceFlag &A, IncludeGraphNode::SourceFlag B) {
101 return A = A | B;
102}
103
Sam McCall3f0243f2018-07-03 08:09:29 +0000104// 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.
113class IncludeStructure {
114public:
115 std::vector<Inclusion> MainFileIncludes;
116
117 // Return all transitively reachable files, and their minimum include depth.
118 // All transitive includes (absolute paths), with their minimum include depth.
119 // Root --> 0, #included file --> 1, etc.
120 // Root is clang's name for a file, which may not be absolute.
121 // Usually it should be SM.getFileEntryForID(SM.getMainFileID())->getName().
122 llvm::StringMap<unsigned> includeDepth(llvm::StringRef Root) const;
123
124 // This updates IncludeDepth(), but not MainFileIncludes.
125 void recordInclude(llvm::StringRef IncludingName,
126 llvm::StringRef IncludedName,
127 llvm::StringRef IncludedRealName);
128
129private:
130 // Identifying files in a way that persists from preamble build to subsequent
131 // builds is surprisingly hard. FileID is unavailable in InclusionDirective(),
Jan Korous2ee64972019-07-30 20:39:39 +0000132 // and RealPathName and UniqueID are not preserved in the preamble.
Sam McCall3f0243f2018-07-03 08:09:29 +0000133 // We use the FileEntry::Name, which is stable, interned into a "file index".
134 // The paths we want to expose are the RealPathName, so store those too.
135 std::vector<std::string> RealPathNames; // In file index order.
136 unsigned fileIndex(llvm::StringRef Name);
137 llvm::StringMap<unsigned> NameToIndex; // Values are file indexes.
138 // Maps a file's index to that of the files it includes.
139 llvm::DenseMap<unsigned, SmallVector<unsigned, 8>> IncludeChildren;
140};
141
Eric Liu155f5a42018-05-14 12:19:16 +0000142/// Returns a PPCallback that visits all inclusions in the main file.
143std::unique_ptr<PPCallbacks>
Sam McCall3f0243f2018-07-03 08:09:29 +0000144collectIncludeStructureCallback(const SourceManager &SM, IncludeStructure *Out);
Eric Liu155f5a42018-05-14 12:19:16 +0000145
Eric Liu63f419a2018-05-15 15:29:32 +0000146// Calculates insertion edit for including a new header in a file.
147class IncludeInserter {
148public:
Eric Liu00d99bd2019-04-11 09:36:36 +0000149 // If \p HeaderSearchInfo is nullptr (e.g. when compile command is
150 // infeasible), this will only try to insert verbatim headers, and
151 // include path of non-verbatim header will not be shortened.
Eric Liu63f419a2018-05-15 15:29:32 +0000152 IncludeInserter(StringRef FileName, StringRef Code,
153 const format::FormatStyle &Style, StringRef BuildDir,
Eric Liu00d99bd2019-04-11 09:36:36 +0000154 HeaderSearch *HeaderSearchInfo)
Eric Liu63f419a2018-05-15 15:29:32 +0000155 : FileName(FileName), Code(Code), BuildDir(BuildDir),
156 HeaderSearchInfo(HeaderSearchInfo),
157 Inserter(FileName, Code, Style.IncludeStyle) {}
158
Eric Liufd9f4262018-09-27 14:27:02 +0000159 void addExisting(const Inclusion &Inc);
Eric Liu63f419a2018-05-15 15:29:32 +0000160
Eric Liu8f3678d2018-06-15 13:34:18 +0000161 /// Checks whether to add an #include of the header into \p File.
162 /// An #include will not be added if:
163 /// - Either \p DeclaringHeader or \p InsertedHeader is already (directly)
164 /// in \p Inclusions (including those included via different paths).
165 /// - \p DeclaringHeader or \p InsertedHeader is the same as \p File.
166 ///
Eric Liu417c8892019-04-16 14:35:49 +0000167 /// \param DeclaringHeader is path of the original header corresponding to \p
Eric Liu8f3678d2018-06-15 13:34:18 +0000168 /// InsertedHeader e.g. the header that declares a symbol.
169 /// \param InsertedHeader The preferred header to be inserted. This could be
Simon Pilgrimcbd8c762018-06-26 17:00:43 +0000170 /// the same as DeclaringHeader but must be provided.
Eric Liu417c8892019-04-16 14:35:49 +0000171 bool shouldInsertInclude(PathRef DeclaringHeader,
Eric Liu8f3678d2018-06-15 13:34:18 +0000172 const HeaderFile &InsertedHeader) const;
173
174 /// Determines the preferred way to #include a file, taking into account the
175 /// search path. Usually this will prefer a shorter representation like
176 /// 'Foo/Bar.h' over a longer one like 'Baz/include/Foo/Bar.h'.
Eric Liu63f419a2018-05-15 15:29:32 +0000177 ///
Sam McCallb324c642019-07-08 18:07:46 +0000178 /// \param InsertedHeader The preferred header to be inserted.
Eric Liu8f3678d2018-06-15 13:34:18 +0000179 ///
Kadir Cetinkaya1f6d9842019-07-03 07:47:19 +0000180 /// \param IncludingFile is the absolute path of the file that InsertedHeader
181 /// will be inserted.
182 ///
Sam McCallb324c642019-07-08 18:07:46 +0000183 /// \return A quoted "path" or <path> to be included, or None if it couldn't
184 /// be shortened.
185 llvm::Optional<std::string>
186 calculateIncludePath(const HeaderFile &InsertedHeader,
187 llvm::StringRef IncludingFile) const;
Eric Liu8f3678d2018-06-15 13:34:18 +0000188
189 /// Calculates an edit that inserts \p VerbatimHeader into code. If the header
190 /// is already included, this returns None.
191 llvm::Optional<TextEdit> insert(llvm::StringRef VerbatimHeader) const;
Eric Liu63f419a2018-05-15 15:29:32 +0000192
193private:
194 StringRef FileName;
195 StringRef Code;
196 StringRef BuildDir;
Eric Liu00d99bd2019-04-11 09:36:36 +0000197 HeaderSearch *HeaderSearchInfo = nullptr;
Eric Liufd9f4262018-09-27 14:27:02 +0000198 llvm::StringSet<> IncludedHeaders; // Both written and resolved.
199 tooling::HeaderIncludes Inserter; // Computers insertion replacement.
Eric Liu63f419a2018-05-15 15:29:32 +0000200};
Eric Liuc5105f92018-02-16 14:15:55 +0000201
202} // namespace clangd
203} // namespace clang
204
205#endif // LLVM_CLANG_TOOLS_EXTRA_CLANGD_HEADERS_H