clang-tools 10.0.0

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 "Compiler.h"
11 #include "Logger.h"
12 #include "SourceCode.h"
13 #include "clang/Frontend/CompilerInstance.h"
14 #include "clang/Frontend/CompilerInvocation.h"
15 #include "clang/Frontend/FrontendActions.h"
16 #include "clang/Lex/HeaderSearch.h"
17 #include "llvm/ADT/StringRef.h"
18 #include "llvm/Support/Path.h"
19
20 namespace clang {
21 namespace clangd {
22 namespace {
23
24 class RecordHeaders : public PPCallbacks {
25 public:
26 RecordHeaders(const SourceManager &SM, IncludeStructure *Out)
27 : SM(SM), Out(Out) {}
28
29 // Record existing #includes - both written and resolved paths. Only #includes
30 // in the main file are collected.
31 void InclusionDirective(SourceLocation HashLoc, const Token & /*IncludeTok*/,
32 llvm::StringRef FileName, bool IsAngled,
33 CharSourceRange FilenameRange, const FileEntry *File,
34 llvm::StringRef /*SearchPath*/,
35 llvm::StringRef /*RelativePath*/,
36 const Module * /*Imported*/,
37 SrcMgr::CharacteristicKind FileKind) override {
38 if (isInsideMainFile(HashLoc, SM)) {
39 Out->MainFileIncludes.emplace_back();
40 auto &Inc = Out->MainFileIncludes.back();
41 Inc.R = halfOpenToRange(SM, FilenameRange);
42 Inc.Written =
43 (IsAngled ? "<" + FileName + ">" : "\"" + FileName + "\"").str();
44 Inc.Resolved = File ? File->tryGetRealPathName() : "";
45 Inc.HashOffset = SM.getFileOffset(HashLoc);
46 Inc.FileKind = FileKind;
47 }
48 if (File) {
49 auto *IncludingFileEntry = SM.getFileEntryForID(SM.getFileID(HashLoc));
50 if (!IncludingFileEntry) {
51 assert(SM.getBufferName(HashLoc).startswith("<") &&
52 "Expected #include location to be a file or <built-in>");
53 // Treat as if included from the main file.
54 IncludingFileEntry = SM.getFileEntryForID(SM.getMainFileID());
55 }
56 Out->recordInclude(IncludingFileEntry->getName(), File->getName(),
57 File->tryGetRealPathName());
58 }
59 }
60
61 private:
62 const SourceManager &SM;
63 IncludeStructure *Out;
64 };
65
66 } // namespace
67
68 bool isLiteralInclude(llvm::StringRef Include) {
69 return Include.startswith("<") || Include.startswith("\"");
70 }
71
72 bool HeaderFile::valid() const {
73 return (Verbatim && isLiteralInclude(File)) ||
74 (!Verbatim && llvm::sys::path::is_absolute(File));
75 }
76
77 llvm::Expected<HeaderFile> toHeaderFile(llvm::StringRef Header,
78 llvm::StringRef HintPath) {
79 if (isLiteralInclude(Header))
80 return HeaderFile{Header.str(), /*Verbatim=*/true};
81 auto U = URI::parse(Header);
82 if (!U)
83 return U.takeError();
84
85 auto IncludePath = URI::includeSpelling(*U);
86 if (!IncludePath)
87 return IncludePath.takeError();
88 if (!IncludePath->empty())
89 return HeaderFile{std::move(*IncludePath), /*Verbatim=*/true};
90
91 auto Resolved = URI::resolve(*U, HintPath);
92 if (!Resolved)
93 return Resolved.takeError();
94 return HeaderFile{std::move(*Resolved), /*Verbatim=*/false};
95 }
96
97 llvm::SmallVector<llvm::StringRef, 1> getRankedIncludes(const Symbol &Sym) {
98 auto Includes = Sym.IncludeHeaders;
99 // Sort in descending order by reference count and header length.
100 llvm::sort(Includes, [](const Symbol::IncludeHeaderWithReferences &LHS,
101 const Symbol::IncludeHeaderWithReferences &RHS) {
102 if (LHS.References == RHS.References)
103 return LHS.IncludeHeader.size() < RHS.IncludeHeader.size();
104 return LHS.References > RHS.References;
105 });
106 llvm::SmallVector<llvm::StringRef, 1> Headers;
107 for (const auto &Include : Includes)
108 Headers.push_back(Include.IncludeHeader);
109 return Headers;
110 }
111
112 std::unique_ptr<PPCallbacks>
113 collectIncludeStructureCallback(const SourceManager &SM,
114 IncludeStructure *Out) {
115 return std::make_unique<RecordHeaders>(SM, Out);
116 }
117
118 void IncludeStructure::recordInclude(llvm::StringRef IncludingName,
119 llvm::StringRef IncludedName,
120 llvm::StringRef IncludedRealName) {
121 auto Child = fileIndex(IncludedName);
122 if (!IncludedRealName.empty() && RealPathNames[Child].empty())
123 RealPathNames[Child] = IncludedRealName;
124 auto Parent = fileIndex(IncludingName);
125 IncludeChildren[Parent].push_back(Child);
126 }
127
128 unsigned IncludeStructure::fileIndex(llvm::StringRef Name) {
129 auto R = NameToIndex.try_emplace(Name, RealPathNames.size());
130 if (R.second)
131 RealPathNames.emplace_back();
132 return R.first->getValue();
133 }
134
135 llvm::StringMap<unsigned>
136 IncludeStructure::includeDepth(llvm::StringRef Root) const {
137 // Include depth 0 is the main file only.
138 llvm::StringMap<unsigned> Result;
139 Result[Root] = 0;
140 std::vector<unsigned> CurrentLevel;
141 llvm::DenseSet<unsigned> Seen;
142 auto It = NameToIndex.find(Root);
143 if (It != NameToIndex.end()) {
144 CurrentLevel.push_back(It->second);
145 Seen.insert(It->second);
146 }
147
148 // Each round of BFS traversal finds the next depth level.
149 std::vector<unsigned> PreviousLevel;
150 for (unsigned Level = 1; !CurrentLevel.empty(); ++Level) {
151 PreviousLevel.clear();
152 PreviousLevel.swap(CurrentLevel);
153 for (const auto &Parent : PreviousLevel) {
154 for (const auto &Child : IncludeChildren.lookup(Parent)) {
155 if (Seen.insert(Child).second) {
156 CurrentLevel.push_back(Child);
157 const auto &Name = RealPathNames[Child];
158 // Can't include files if we don't have their real path.
159 if (!Name.empty())
160 Result[Name] = Level;
161 }
162 }
163 }
164 }
165 return Result;
166 }
167
168 void IncludeInserter::addExisting(const Inclusion &Inc) {
169 IncludedHeaders.insert(Inc.Written);
170 if (!Inc.Resolved.empty())
171 IncludedHeaders.insert(Inc.Resolved);
172 }
173
174 /// FIXME(ioeric): we might not want to insert an absolute include path if the
175 /// path is not shortened.
176 bool IncludeInserter::shouldInsertInclude(
177 PathRef DeclaringHeader, const HeaderFile &InsertedHeader) const {
178 assert(InsertedHeader.valid());
179 if (!HeaderSearchInfo && !InsertedHeader.Verbatim)
180 return false;
181 if (FileName == DeclaringHeader || FileName == InsertedHeader.File)
182 return false;
183 auto Included = [&](llvm::StringRef Header) {
184 return IncludedHeaders.find(Header) != IncludedHeaders.end();
185 };
186 return !Included(DeclaringHeader) && !Included(InsertedHeader.File);
187 }
188
189 llvm::Optional<std::string>
190 IncludeInserter::calculateIncludePath(const HeaderFile &InsertedHeader,
191 llvm::StringRef IncludingFile) const {
192 assert(InsertedHeader.valid());
193 if (InsertedHeader.Verbatim)
194 return InsertedHeader.File;
195 bool IsSystem = false;
196 std::string Suggested;
197 if (HeaderSearchInfo) {
198 Suggested = HeaderSearchInfo->suggestPathToFileForDiagnostics(
199 InsertedHeader.File, BuildDir, IncludingFile, &IsSystem);
200 } else {
201 // Calculate include relative to including file only.
202 StringRef IncludingDir = llvm::sys::path::parent_path(IncludingFile);
203 SmallString<256> RelFile(InsertedHeader.File);
204 // Replacing with "" leaves "/RelFile" if IncludingDir doesn't end in "/".
205 llvm::sys::path::replace_path_prefix(RelFile, IncludingDir, "./");
206 Suggested = llvm::sys::path::convert_to_slash(
207 llvm::sys::path::remove_leading_dotslash(RelFile));
208 }
209 // FIXME: should we allow (some limited number of) "../header.h"?
210 if (llvm::sys::path::is_absolute(Suggested))
211 return None;
212 if (IsSystem)
213 Suggested = "<" + Suggested + ">";
214 else
215 Suggested = "\"" + Suggested + "\"";
216 return Suggested;
217 }
218
219 llvm::Optional<TextEdit>
220 IncludeInserter::insert(llvm::StringRef VerbatimHeader) const {
221 llvm::Optional<TextEdit> Edit = None;
222 if (auto Insertion = Inserter.insert(VerbatimHeader.trim("\"<>"),
223 VerbatimHeader.startswith("<")))
224 Edit = replacementToEdit(Code, *Insertion);
225 return Edit;
226 }
227
228 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const Inclusion &Inc) {
229 return OS << Inc.Written << " = "
230 << (Inc.Resolved.empty() ? Inc.Resolved : "[unresolved]") << " at "
231 << Inc.R;
232 }
233
234 } // namespace clangd
235 } // namespace clang
Code
std::string Code
Definition: FindTargetTests.cpp:67
clang::clangd::HeaderFile::valid
bool valid() const
Definition: Headers.cpp:72
Parent
const Node * Parent
Definition: ExtractFunction.cpp:148
clang::clangd::Symbol::IncludeHeaderWithReferences::References
unsigned References
The number of translation units that reference this symbol and include this header.
Definition: Symbol.h:104
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
clang::clangd::isInsideMainFile
bool isInsideMainFile(SourceLocation Loc, const SourceManager &SM)
Returns true iff Loc is inside the main file.
Definition: SourceCode.cpp:534
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::IncludeInserter::insert
llvm::Optional< TextEdit > insert(llvm::StringRef VerbatimHeader) const
Calculates an edit that inserts VerbatimHeader into code.
Definition: Headers.cpp:220
clang::clangd::IncludeStructure
Definition: Headers.h:109
Headers.h
clang::clangd::Symbol::IncludeHeaderWithReferences
Definition: Symbol.h:87
clang::clangd::Inclusion
Definition: Headers.h:52
clang::clangd::Inclusion::Written
std::string Written
Definition: Headers.h:54
clang::clangd::Symbol::IncludeHeaders
llvm::SmallVector< IncludeHeaderWithReferences, 1 > IncludeHeaders
One Symbol can potentially be included via different headers.
Definition: Symbol.h:111
clang::clangd::IncludeInserter::addExisting
void addExisting(const Inclusion &Inc)
Definition: Headers.cpp:168
Compiler.h
IsAngled
bool IsAngled
true if this was an include with angle brackets
Definition: IncludeOrderCheck.cpp:40
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
PPCallbacks
clang::clangd::IncludeStructure::recordInclude
void recordInclude(llvm::StringRef IncludingName, llvm::StringRef IncludedName, llvm::StringRef IncludedRealName)
Definition: Headers.cpp:118
Logger.h
clang::clangd::Symbol::IncludeHeaderWithReferences::IncludeHeader
llvm::StringRef IncludeHeader
This can be either a URI of the header to be #include&#39;d for this symbol, or a literal header quoted w...
Definition: Symbol.h:101
clang::clangd::Symbol
The class presents a C++ symbol, e.g.
Definition: Symbol.h:36
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
clang::clangd::CompletionItemKind::Module
clang::clangd::replacementToEdit
TextEdit replacementToEdit(llvm::StringRef Code, const tooling::Replacement &R)
Definition: SourceCode.cpp:606
clang::clangd::IncludeStructure::includeDepth
llvm::StringMap< unsigned > includeDepth(llvm::StringRef Root) const
Definition: Headers.cpp:136
clang::clangd::HeaderFile::File
std::string File
Definition: Headers.h:34
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:190
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::URI::resolve
static llvm::Expected< std::string > resolve(const URI &U, llvm::StringRef HintPath="")
Resolves the absolute path of U.
Definition: URI.cpp:233
clang::clangd::Inclusion::R
Range R
Definition: Headers.h:53
clang::clangd::URI::includeSpelling
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:261
clang::clangd::URI::parse
static llvm::Expected< URI > parse(llvm::StringRef Uri)
Parse a URI string "<scheme>:[//<authority>/]<path>".
Definition: URI.cpp:164
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:176
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::CompletionItemKind::File
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::Edit
A set of edits generated for a single file.
Definition: SourceCode.h:204
clang::clangd::halfOpenToRange
Range halfOpenToRange(const SourceManager &SM, CharSourceRange R)
Definition: SourceCode.cpp:581