clang-tools 17.0.0git
Headers.cpp
Go to the documentation of this file.
1//===--- Headers.cpp - 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#include "Headers.h"
10#include "Preamble.h"
11#include "SourceCode.h"
12#include "clang/Basic/SourceLocation.h"
13#include "clang/Basic/SourceManager.h"
14#include "clang/Frontend/CompilerInstance.h"
15#include "clang/Lex/HeaderSearch.h"
16#include "clang/Lex/PPCallbacks.h"
17#include "clang/Lex/Preprocessor.h"
18#include "clang/Tooling/Inclusions/HeaderAnalysis.h"
19#include "llvm/ADT/SmallVector.h"
20#include "llvm/ADT/StringRef.h"
21#include "llvm/Support/Path.h"
22#include <cstring>
23#include <optional>
24
25namespace clang {
26namespace clangd {
27
29public:
30 RecordHeaders(const CompilerInstance &CI, IncludeStructure *Out)
31 : SM(CI.getSourceManager()),
32 Out(Out) {}
33
34 // Record existing #includes - both written and resolved paths. Only #includes
35 // in the main file are collected.
36 void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,
37 llvm::StringRef FileName, bool IsAngled,
38 CharSourceRange /*FilenameRange*/,
39 OptionalFileEntryRef File,
40 llvm::StringRef /*SearchPath*/,
41 llvm::StringRef /*RelativePath*/,
42 const clang::Module * /*Imported*/,
43 SrcMgr::CharacteristicKind FileKind) override {
44 auto MainFID = SM.getMainFileID();
45 // If an include is part of the preamble patch, translate #line directives.
46 if (InBuiltinFile)
47 HashLoc = translatePreamblePatchLocation(HashLoc, SM);
48
49 // Record main-file inclusions (including those mapped from the preamble
50 // patch).
51 if (isInsideMainFile(HashLoc, SM)) {
52 Out->MainFileIncludes.emplace_back();
53 auto &Inc = Out->MainFileIncludes.back();
54 Inc.Written =
55 (IsAngled ? "<" + FileName + ">" : "\"" + FileName + "\"").str();
56 Inc.Resolved =
57 std::string(File ? File->getFileEntry().tryGetRealPathName() : "");
58 Inc.HashOffset = SM.getFileOffset(HashLoc);
59 Inc.HashLine =
60 SM.getLineNumber(SM.getFileID(HashLoc), Inc.HashOffset) - 1;
61 Inc.FileKind = FileKind;
62 Inc.Directive = IncludeTok.getIdentifierInfo()->getPPKeywordID();
63 if (File) {
65 Inc.HeaderID = static_cast<unsigned>(HID);
66 if (IsAngled)
67 if (auto StdlibHeader = tooling::stdlib::Header::named(Inc.Written)) {
68 auto &IDs = Out->StdlibHeaders[*StdlibHeader];
69 // Few physical files for one stdlib header name, linear scan is ok.
70 if (!llvm::is_contained(IDs, HID))
71 IDs.push_back(HID);
72 }
73 }
74 Out->MainFileIncludesBySpelling.try_emplace(Inc.Written)
75 .first->second.push_back(Out->MainFileIncludes.size() - 1);
76 }
77
78 // Record include graph (not just for main-file includes)
79 if (File) {
80 auto IncludingFileEntry = SM.getFileEntryRefForID(SM.getFileID(HashLoc));
81 if (!IncludingFileEntry) {
82 assert(SM.getBufferName(HashLoc).startswith("<") &&
83 "Expected #include location to be a file or <built-in>");
84 // Treat as if included from the main file.
85 IncludingFileEntry = SM.getFileEntryRefForID(MainFID);
86 }
87 auto IncludingID = Out->getOrCreateID(*IncludingFileEntry),
88 IncludedID = Out->getOrCreateID(*File);
89 Out->IncludeChildren[IncludingID].push_back(IncludedID);
90 }
91 }
92
93 void FileChanged(SourceLocation Loc, FileChangeReason Reason,
94 SrcMgr::CharacteristicKind FileType,
95 FileID PrevFID) override {
96 switch (Reason) {
97 case PPCallbacks::EnterFile:
98 ++Level;
99 if (BuiltinFile.isInvalid() && SM.isWrittenInBuiltinFile(Loc)) {
100 BuiltinFile = SM.getFileID(Loc);
101 InBuiltinFile = true;
102 }
103 break;
104 case PPCallbacks::ExitFile: {
105 --Level;
106 if (PrevFID == BuiltinFile)
107 InBuiltinFile = false;
108 break;
109 }
110 case PPCallbacks::RenameFile:
111 case PPCallbacks::SystemHeaderPragma:
112 break;
113 }
114 }
115
116private:
117 // Keeps track of include depth for the current file. It's 1 for main file.
118 int Level = 0;
119 bool inMainFile() const { return Level == 1; }
120
121 const SourceManager &SM;
122 // Set after entering the <built-in> file.
123 FileID BuiltinFile;
124 // Indicates whether <built-in> file is part of include stack.
125 bool InBuiltinFile = false;
126
127 IncludeStructure *Out;
128};
129
130bool isLiteralInclude(llvm::StringRef Include) {
131 return Include.startswith("<") || Include.startswith("\"");
132}
133
134bool HeaderFile::valid() const {
135 return (Verbatim && isLiteralInclude(File)) ||
136 (!Verbatim && llvm::sys::path::is_absolute(File));
137}
138
139llvm::Expected<HeaderFile> toHeaderFile(llvm::StringRef Header,
140 llvm::StringRef HintPath) {
141 if (isLiteralInclude(Header))
142 return HeaderFile{Header.str(), /*Verbatim=*/true};
143 auto U = URI::parse(Header);
144 if (!U)
145 return U.takeError();
146
147 auto IncludePath = URI::includeSpelling(*U);
148 if (!IncludePath)
149 return IncludePath.takeError();
150 if (!IncludePath->empty())
151 return HeaderFile{std::move(*IncludePath), /*Verbatim=*/true};
152
153 auto Resolved = URI::resolve(*U, HintPath);
154 if (!Resolved)
155 return Resolved.takeError();
156 return HeaderFile{std::move(*Resolved), /*Verbatim=*/false};
157}
158
159llvm::SmallVector<SymbolInclude, 1> getRankedIncludes(const Symbol &Sym) {
160 auto Includes = Sym.IncludeHeaders;
161 // Sort in descending order by reference count and header length.
162 llvm::sort(Includes, [](const Symbol::IncludeHeaderWithReferences &LHS,
164 if (LHS.References == RHS.References)
165 return LHS.IncludeHeader.size() < RHS.IncludeHeader.size();
166 return LHS.References > RHS.References;
167 });
168 llvm::SmallVector<SymbolInclude, 1> Headers;
169 for (const auto &Include : Includes)
170 Headers.push_back({Include.IncludeHeader, Include.supportedDirectives()});
171 return Headers;
172}
173
174void IncludeStructure::collect(const CompilerInstance &CI) {
175 auto &SM = CI.getSourceManager();
176 MainFileEntry = SM.getFileEntryForID(SM.getMainFileID());
177 auto Collector = std::make_unique<RecordHeaders>(CI, this);
178 CI.getPreprocessor().addPPCallbacks(std::move(Collector));
179}
180
181std::optional<IncludeStructure::HeaderID>
182IncludeStructure::getID(const FileEntry *Entry) const {
183 // HeaderID of the main file is always 0;
184 if (Entry == MainFileEntry) {
185 return static_cast<IncludeStructure::HeaderID>(0u);
186 }
187 auto It = UIDToIndex.find(Entry->getUniqueID());
188 if (It == UIDToIndex.end())
189 return std::nullopt;
190 return It->second;
191}
192
194 // Main file's FileEntry was not known at IncludeStructure creation time.
195 if (&Entry.getFileEntry() == MainFileEntry) {
196 if (RealPathNames.front().empty())
197 RealPathNames.front() = MainFileEntry->tryGetRealPathName().str();
198 return MainFileID;
199 }
200 auto R = UIDToIndex.try_emplace(
201 Entry.getUniqueID(),
202 static_cast<IncludeStructure::HeaderID>(RealPathNames.size()));
203 if (R.second)
204 RealPathNames.emplace_back();
205 IncludeStructure::HeaderID Result = R.first->getSecond();
206 std::string &RealPathName = RealPathNames[static_cast<unsigned>(Result)];
207 if (RealPathName.empty())
208 RealPathName = Entry.getFileEntry().tryGetRealPathName().str();
209 return Result;
210}
211
212llvm::DenseMap<IncludeStructure::HeaderID, unsigned>
214 // Include depth 0 is the main file only.
215 llvm::DenseMap<HeaderID, unsigned> Result;
216 assert(static_cast<unsigned>(Root) < RealPathNames.size());
217 Result[Root] = 0;
218 std::vector<IncludeStructure::HeaderID> CurrentLevel;
219 CurrentLevel.push_back(Root);
220 llvm::DenseSet<IncludeStructure::HeaderID> Seen;
221 Seen.insert(Root);
222
223 // Each round of BFS traversal finds the next depth level.
224 std::vector<IncludeStructure::HeaderID> PreviousLevel;
225 for (unsigned Level = 1; !CurrentLevel.empty(); ++Level) {
226 PreviousLevel.clear();
227 PreviousLevel.swap(CurrentLevel);
228 for (const auto &Parent : PreviousLevel) {
229 for (const auto &Child : IncludeChildren.lookup(Parent)) {
230 if (Seen.insert(Child).second) {
231 CurrentLevel.push_back(Child);
232 Result[Child] = Level;
233 }
234 }
235 }
236 }
237 return Result;
238}
239
240llvm::SmallVector<const Inclusion *>
241IncludeStructure::mainFileIncludesWithSpelling(llvm::StringRef Spelling) const {
242 llvm::SmallVector<const Inclusion *> Includes;
243 for (auto Idx : MainFileIncludesBySpelling.lookup(Spelling))
244 Includes.push_back(&MainFileIncludes[Idx]);
245 return Includes;
246}
247
249 IncludedHeaders.insert(Inc.Written);
250 if (!Inc.Resolved.empty())
251 IncludedHeaders.insert(Inc.Resolved);
252}
253
254/// FIXME(ioeric): we might not want to insert an absolute include path if the
255/// path is not shortened.
257 PathRef DeclaringHeader, const HeaderFile &InsertedHeader) const {
258 assert(InsertedHeader.valid());
259 if (!HeaderSearchInfo && !InsertedHeader.Verbatim)
260 return false;
261 if (FileName == DeclaringHeader || FileName == InsertedHeader.File)
262 return false;
263 auto Included = [&](llvm::StringRef Header) {
264 return IncludedHeaders.contains(Header);
265 };
266 return !Included(DeclaringHeader) && !Included(InsertedHeader.File);
267}
268
269std::optional<std::string>
271 llvm::StringRef IncludingFile) const {
272 assert(InsertedHeader.valid());
273 if (InsertedHeader.Verbatim)
274 return InsertedHeader.File;
275 bool IsSystem = false;
276 std::string Suggested;
277 if (HeaderSearchInfo) {
278 Suggested = HeaderSearchInfo->suggestPathToFileForDiagnostics(
279 InsertedHeader.File, BuildDir, IncludingFile, &IsSystem);
280 } else {
281 // Calculate include relative to including file only.
282 StringRef IncludingDir = llvm::sys::path::parent_path(IncludingFile);
283 SmallString<256> RelFile(InsertedHeader.File);
284 // Replacing with "" leaves "/RelFile" if IncludingDir doesn't end in "/".
285 llvm::sys::path::replace_path_prefix(RelFile, IncludingDir, "./");
286 Suggested = llvm::sys::path::convert_to_slash(
287 llvm::sys::path::remove_leading_dotslash(RelFile));
288 }
289 // FIXME: should we allow (some limited number of) "../header.h"?
290 if (llvm::sys::path::is_absolute(Suggested))
291 return std::nullopt;
292 if (IsSystem)
293 Suggested = "<" + Suggested + ">";
294 else
295 Suggested = "\"" + Suggested + "\"";
296 return Suggested;
297}
298
299std::optional<TextEdit>
300IncludeInserter::insert(llvm::StringRef VerbatimHeader,
301 tooling::IncludeDirective Directive) const {
302 std::optional<TextEdit> Edit;
303 if (auto Insertion =
304 Inserter.insert(VerbatimHeader.trim("\"<>"),
305 VerbatimHeader.startswith("<"), Directive))
306 Edit = replacementToEdit(Code, *Insertion);
307 return Edit;
308}
309
310llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const Inclusion &Inc) {
311 return OS << Inc.Written << " = "
312 << (!Inc.Resolved.empty() ? Inc.Resolved : "[unresolved]")
313 << " at line" << Inc.HashLine;
314}
315
316bool operator==(const Inclusion &LHS, const Inclusion &RHS) {
317 return std::tie(LHS.Directive, LHS.FileKind, LHS.HashOffset, LHS.HashLine,
318 LHS.Resolved, LHS.Written) ==
319 std::tie(RHS.Directive, RHS.FileKind, RHS.HashOffset, RHS.HashLine,
320 RHS.Resolved, RHS.Written);
321}
322
323} // namespace clangd
324} // namespace clang
CompiledFragmentImpl & Out
ASTNode Root
Definition: DumpAST.cpp:333
const Node * Parent
bool IsAngled
true if this was an include with angle brackets
StringRef FileName
SourceLocation Loc
const MacroDirective * Directive
std::unique_ptr< CompilerInvocation > CI
llvm::raw_string_ostream OS
Definition: TraceTests.cpp:160
void addExisting(const Inclusion &Inc)
Definition: Headers.cpp:248
std::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:270
bool shouldInsertInclude(PathRef DeclaringHeader, const HeaderFile &InsertedHeader) const
Checks whether to add an #include of the header into File.
Definition: Headers.cpp:256
std::optional< TextEdit > insert(llvm::StringRef VerbatimHeader, tooling::IncludeDirective Directive) const
Calculates an edit that inserts VerbatimHeader into code.
Definition: Headers.cpp:300
void FileChanged(SourceLocation Loc, FileChangeReason Reason, SrcMgr::CharacteristicKind FileType, FileID PrevFID) override
Definition: Headers.cpp:93
RecordHeaders(const CompilerInstance &CI, IncludeStructure *Out)
Definition: Headers.cpp:30
void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok, llvm::StringRef FileName, bool IsAngled, CharSourceRange, OptionalFileEntryRef File, llvm::StringRef, llvm::StringRef, const clang::Module *, SrcMgr::CharacteristicKind FileKind) override
Definition: Headers.cpp:36
llvm::SmallVector< const Inclusion * > mainFileIncludesWithSpelling(llvm::StringRef Spelling) const
Definition: Headers.cpp:241
static const HeaderID MainFileID
Definition: Headers.h:179
llvm::DenseMap< HeaderID, unsigned > includeDepth(HeaderID Root=MainFileID) const
Definition: Headers.cpp:213
std::vector< Inclusion > MainFileIncludes
Definition: Headers.h:174
llvm::DenseMap< tooling::stdlib::Header, llvm::SmallVector< HeaderID > > StdlibHeaders
Definition: Headers.h:172
HeaderID getOrCreateID(FileEntryRef Entry)
Definition: Headers.cpp:193
void collect(const CompilerInstance &CI)
Definition: Headers.cpp:174
std::optional< HeaderID > getID(const FileEntry *Entry) const
Definition: Headers.cpp:182
llvm::DenseMap< HeaderID, SmallVector< HeaderID > > IncludeChildren
Definition: Headers.h:169
static llvm::Expected< std::string > includeSpelling(const URI &U)
Gets the preferred spelling of this file for #include, if there is one, e.g.
Definition: URI.cpp:273
static llvm::Expected< std::string > resolve(const URI &U, llvm::StringRef HintPath="")
Resolves the absolute path of U.
Definition: URI.cpp:245
static llvm::Expected< URI > parse(llvm::StringRef Uri)
Parse a URI string "<scheme>:[//<authority>/]<path>".
Definition: URI.cpp:177
bool isLiteralInclude(llvm::StringRef Include)
Returns true if Include is literal include like "path" or <path>.
Definition: Headers.cpp:130
bool isInsideMainFile(SourceLocation Loc, const SourceManager &SM)
Returns true iff Loc is inside the main file.
Definition: SourceCode.cpp:419
bool operator==(const Inclusion &LHS, const Inclusion &RHS)
Definition: Headers.cpp:316
llvm::raw_ostream & operator<<(llvm::raw_ostream &OS, const CodeCompletion &C)
SourceLocation translatePreamblePatchLocation(SourceLocation Loc, const SourceManager &SM)
Translates locations inside preamble patch to their main-file equivalent using presumed locations.
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:139
llvm::SmallVector< SymbolInclude, 1 > getRankedIncludes(const Symbol &Sym)
Definition: Headers.cpp:159
llvm::StringRef PathRef
A typedef to represent a ref to file path.
Definition: Path.h:29
TextEdit replacementToEdit(llvm::StringRef Code, const tooling::Replacement &R)
Definition: SourceCode.cpp:500
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
A set of edits generated for a single file.
Definition: SourceCode.h:185
Represents a header file to be #include'd.
Definition: Headers.h:40
bool Verbatim
If this is true, File is a literal string quoted with <> or "" that can be #included directly; otherw...
Definition: Headers.h:44
std::string Written
Definition: Headers.h:70
tok::PPKeywordKind Directive
Definition: Headers.h:69
SrcMgr::CharacteristicKind FileKind
Definition: Headers.h:74
uint32_t References
The number of translation units that reference this symbol and include this header.
Definition: Symbol.h:119
llvm::StringRef IncludeHeader
This can be either a URI of the header to be #include'd for this symbol, or a literal header quoted w...
Definition: Symbol.h:116
The class presents a C++ symbol, e.g.
Definition: Symbol.h:39
llvm::SmallVector< IncludeHeaderWithReferences, 1 > IncludeHeaders
One Symbol can potentially be included via different headers.
Definition: Symbol.h:133