blob: 876645cd6a50391d78ac0358e538a93416033cac [file] [log] [blame]
Eric Liuc5105f92018-02-16 14:15:55 +00001//===--- Headers.cpp - 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#include "Headers.h"
10#include "Compiler.h"
Kadir Cetinkaya538c2752020-05-14 12:26:47 +020011#include "Preamble.h"
Eric Liu155f5a42018-05-14 12:19:16 +000012#include "SourceCode.h"
Sam McCallad97ccf2020-04-28 17:49:17 +020013#include "support/Logger.h"
Kadir Cetinkaya6d6d48a2020-05-06 16:20:31 +020014#include "clang/Basic/SourceLocation.h"
15#include "clang/Basic/SourceManager.h"
Eric Liuc5105f92018-02-16 14:15:55 +000016#include "clang/Frontend/CompilerInstance.h"
17#include "clang/Frontend/CompilerInvocation.h"
18#include "clang/Frontend/FrontendActions.h"
19#include "clang/Lex/HeaderSearch.h"
Kadir Cetinkaya1f6d9842019-07-03 07:47:19 +000020#include "llvm/ADT/StringRef.h"
Eric Liu709bde82018-02-19 18:48:44 +000021#include "llvm/Support/Path.h"
Eric Liuc5105f92018-02-16 14:15:55 +000022
23namespace clang {
24namespace clangd {
25namespace {
26
27class RecordHeaders : public PPCallbacks {
28public:
Sam McCall3f0243f2018-07-03 08:09:29 +000029 RecordHeaders(const SourceManager &SM, IncludeStructure *Out)
30 : SM(SM), Out(Out) {}
Eric Liuc5105f92018-02-16 14:15:55 +000031
Eric Liu155f5a42018-05-14 12:19:16 +000032 // Record existing #includes - both written and resolved paths. Only #includes
33 // in the main file are collected.
Kadir Cetinkaya6e017182020-04-15 22:00:19 +020034 void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000035 llvm::StringRef FileName, bool IsAngled,
Kadir Cetinkaya6d6d48a2020-05-06 16:20:31 +020036 CharSourceRange /*FilenameRange*/,
37 const FileEntry *File, llvm::StringRef /*SearchPath*/,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000038 llvm::StringRef /*RelativePath*/,
Julie Hockett546943f2018-05-10 19:13:14 +000039 const Module * /*Imported*/,
Sam McCall991e3162018-11-20 10:58:48 +000040 SrcMgr::CharacteristicKind FileKind) override {
Kadir Cetinkaya6d6d48a2020-05-06 16:20:31 +020041 auto MainFID = SM.getMainFileID();
42 // If an include is part of the preamble patch, translate #line directives.
Kadir Cetinkaya538c2752020-05-14 12:26:47 +020043 if (InBuiltinFile)
44 HashLoc = translatePreamblePatchLocation(HashLoc, SM);
Kadir Cetinkaya6d6d48a2020-05-06 16:20:31 +020045
46 // Record main-file inclusions (including those mapped from the preamble
47 // patch).
Haojian Wu6ae86ea2019-07-19 08:33:39 +000048 if (isInsideMainFile(HashLoc, SM)) {
Sam McCall991e3162018-11-20 10:58:48 +000049 Out->MainFileIncludes.emplace_back();
50 auto &Inc = Out->MainFileIncludes.back();
Sam McCall991e3162018-11-20 10:58:48 +000051 Inc.Written =
52 (IsAngled ? "<" + FileName + ">" : "\"" + FileName + "\"").str();
Benjamin Krameradcd0262020-01-28 20:23:46 +010053 Inc.Resolved = std::string(File ? File->tryGetRealPathName() : "");
Sam McCall991e3162018-11-20 10:58:48 +000054 Inc.HashOffset = SM.getFileOffset(HashLoc);
Kadir Cetinkayad8700162020-05-04 10:48:19 +020055 Inc.HashLine =
56 SM.getLineNumber(SM.getFileID(HashLoc), Inc.HashOffset) - 1;
Sam McCall991e3162018-11-20 10:58:48 +000057 Inc.FileKind = FileKind;
Kadir Cetinkaya6e017182020-04-15 22:00:19 +020058 Inc.Directive = IncludeTok.getIdentifierInfo()->getPPKeywordID();
Sam McCall991e3162018-11-20 10:58:48 +000059 }
Kadir Cetinkaya6d6d48a2020-05-06 16:20:31 +020060
61 // Record include graph (not just for main-file includes)
Sam McCall3f0243f2018-07-03 08:09:29 +000062 if (File) {
63 auto *IncludingFileEntry = SM.getFileEntryForID(SM.getFileID(HashLoc));
64 if (!IncludingFileEntry) {
65 assert(SM.getBufferName(HashLoc).startswith("<") &&
66 "Expected #include location to be a file or <built-in>");
67 // Treat as if included from the main file.
Kadir Cetinkaya6d6d48a2020-05-06 16:20:31 +020068 IncludingFileEntry = SM.getFileEntryForID(MainFID);
Sam McCall3f0243f2018-07-03 08:09:29 +000069 }
70 Out->recordInclude(IncludingFileEntry->getName(), File->getName(),
71 File->tryGetRealPathName());
72 }
Eric Liuc5105f92018-02-16 14:15:55 +000073 }
74
Kadir Cetinkaya6d6d48a2020-05-06 16:20:31 +020075 void FileChanged(SourceLocation Loc, FileChangeReason Reason,
76 SrcMgr::CharacteristicKind FileType,
77 FileID PrevFID) override {
78 switch (Reason) {
79 case PPCallbacks::EnterFile:
80 if (BuiltinFile.isInvalid() && SM.isWrittenInBuiltinFile(Loc)) {
81 BuiltinFile = SM.getFileID(Loc);
82 InBuiltinFile = true;
83 }
84 break;
85 case PPCallbacks::ExitFile:
86 if (PrevFID == BuiltinFile)
87 InBuiltinFile = false;
88 break;
89 case PPCallbacks::RenameFile:
90 case PPCallbacks::SystemHeaderPragma:
91 break;
92 }
93 }
94
Eric Liuc5105f92018-02-16 14:15:55 +000095private:
Eric Liu155f5a42018-05-14 12:19:16 +000096 const SourceManager &SM;
Kadir Cetinkaya6d6d48a2020-05-06 16:20:31 +020097 // Set after entering the <built-in> file.
98 FileID BuiltinFile;
99 // Indicates whether <built-in> file is part of include stack.
100 bool InBuiltinFile = false;
101
Sam McCall3f0243f2018-07-03 08:09:29 +0000102 IncludeStructure *Out;
Eric Liuc5105f92018-02-16 14:15:55 +0000103};
104
105} // namespace
106
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000107bool isLiteralInclude(llvm::StringRef Include) {
Eric Liu6c8e8582018-02-26 08:32:13 +0000108 return Include.startswith("<") || Include.startswith("\"");
109}
110
111bool HeaderFile::valid() const {
112 return (Verbatim && isLiteralInclude(File)) ||
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000113 (!Verbatim && llvm::sys::path::is_absolute(File));
Eric Liu6c8e8582018-02-26 08:32:13 +0000114}
115
Eric Liudd662772019-01-28 14:01:55 +0000116llvm::Expected<HeaderFile> toHeaderFile(llvm::StringRef Header,
117 llvm::StringRef HintPath) {
118 if (isLiteralInclude(Header))
119 return HeaderFile{Header.str(), /*Verbatim=*/true};
120 auto U = URI::parse(Header);
121 if (!U)
122 return U.takeError();
123
124 auto IncludePath = URI::includeSpelling(*U);
125 if (!IncludePath)
126 return IncludePath.takeError();
127 if (!IncludePath->empty())
128 return HeaderFile{std::move(*IncludePath), /*Verbatim=*/true};
129
130 auto Resolved = URI::resolve(*U, HintPath);
131 if (!Resolved)
132 return Resolved.takeError();
133 return HeaderFile{std::move(*Resolved), /*Verbatim=*/false};
134}
135
136llvm::SmallVector<llvm::StringRef, 1> getRankedIncludes(const Symbol &Sym) {
137 auto Includes = Sym.IncludeHeaders;
138 // Sort in descending order by reference count and header length.
139 llvm::sort(Includes, [](const Symbol::IncludeHeaderWithReferences &LHS,
140 const Symbol::IncludeHeaderWithReferences &RHS) {
141 if (LHS.References == RHS.References)
142 return LHS.IncludeHeader.size() < RHS.IncludeHeader.size();
143 return LHS.References > RHS.References;
144 });
145 llvm::SmallVector<llvm::StringRef, 1> Headers;
146 for (const auto &Include : Includes)
147 Headers.push_back(Include.IncludeHeader);
148 return Headers;
149}
150
Eric Liu155f5a42018-05-14 12:19:16 +0000151std::unique_ptr<PPCallbacks>
Sam McCall3f0243f2018-07-03 08:09:29 +0000152collectIncludeStructureCallback(const SourceManager &SM,
153 IncludeStructure *Out) {
Jonas Devlieghere1c705d92019-08-14 23:52:23 +0000154 return std::make_unique<RecordHeaders>(SM, Out);
Sam McCall3f0243f2018-07-03 08:09:29 +0000155}
156
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000157void IncludeStructure::recordInclude(llvm::StringRef IncludingName,
158 llvm::StringRef IncludedName,
159 llvm::StringRef IncludedRealName) {
Sam McCall3f0243f2018-07-03 08:09:29 +0000160 auto Child = fileIndex(IncludedName);
161 if (!IncludedRealName.empty() && RealPathNames[Child].empty())
Benjamin Krameradcd0262020-01-28 20:23:46 +0100162 RealPathNames[Child] = std::string(IncludedRealName);
Sam McCall3f0243f2018-07-03 08:09:29 +0000163 auto Parent = fileIndex(IncludingName);
164 IncludeChildren[Parent].push_back(Child);
165}
166
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000167unsigned IncludeStructure::fileIndex(llvm::StringRef Name) {
Sam McCall3f0243f2018-07-03 08:09:29 +0000168 auto R = NameToIndex.try_emplace(Name, RealPathNames.size());
169 if (R.second)
170 RealPathNames.emplace_back();
171 return R.first->getValue();
172}
173
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000174llvm::StringMap<unsigned>
175IncludeStructure::includeDepth(llvm::StringRef Root) const {
Sam McCall3f0243f2018-07-03 08:09:29 +0000176 // Include depth 0 is the main file only.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000177 llvm::StringMap<unsigned> Result;
Sam McCall3f0243f2018-07-03 08:09:29 +0000178 Result[Root] = 0;
179 std::vector<unsigned> CurrentLevel;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000180 llvm::DenseSet<unsigned> Seen;
Sam McCall3f0243f2018-07-03 08:09:29 +0000181 auto It = NameToIndex.find(Root);
182 if (It != NameToIndex.end()) {
183 CurrentLevel.push_back(It->second);
184 Seen.insert(It->second);
185 }
186
187 // Each round of BFS traversal finds the next depth level.
188 std::vector<unsigned> PreviousLevel;
189 for (unsigned Level = 1; !CurrentLevel.empty(); ++Level) {
190 PreviousLevel.clear();
191 PreviousLevel.swap(CurrentLevel);
192 for (const auto &Parent : PreviousLevel) {
193 for (const auto &Child : IncludeChildren.lookup(Parent)) {
194 if (Seen.insert(Child).second) {
195 CurrentLevel.push_back(Child);
196 const auto &Name = RealPathNames[Child];
197 // Can't include files if we don't have their real path.
198 if (!Name.empty())
199 Result[Name] = Level;
200 }
201 }
202 }
203 }
204 return Result;
Eric Liu155f5a42018-05-14 12:19:16 +0000205}
206
Eric Liufd9f4262018-09-27 14:27:02 +0000207void IncludeInserter::addExisting(const Inclusion &Inc) {
208 IncludedHeaders.insert(Inc.Written);
209 if (!Inc.Resolved.empty())
210 IncludedHeaders.insert(Inc.Resolved);
211}
212
Eric Liuc5105f92018-02-16 14:15:55 +0000213/// FIXME(ioeric): we might not want to insert an absolute include path if the
214/// path is not shortened.
Eric Liu8f3678d2018-06-15 13:34:18 +0000215bool IncludeInserter::shouldInsertInclude(
Eric Liu417c8892019-04-16 14:35:49 +0000216 PathRef DeclaringHeader, const HeaderFile &InsertedHeader) const {
217 assert(InsertedHeader.valid());
Eric Liu00d99bd2019-04-11 09:36:36 +0000218 if (!HeaderSearchInfo && !InsertedHeader.Verbatim)
219 return false;
Eric Liu417c8892019-04-16 14:35:49 +0000220 if (FileName == DeclaringHeader || FileName == InsertedHeader.File)
Eric Liu8f3678d2018-06-15 13:34:18 +0000221 return false;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000222 auto Included = [&](llvm::StringRef Header) {
Eric Liu155f5a42018-05-14 12:19:16 +0000223 return IncludedHeaders.find(Header) != IncludedHeaders.end();
Eric Liu6c8e8582018-02-26 08:32:13 +0000224 };
Eric Liu417c8892019-04-16 14:35:49 +0000225 return !Included(DeclaringHeader) && !Included(InsertedHeader.File);
Eric Liu8f3678d2018-06-15 13:34:18 +0000226}
Eric Liuc5105f92018-02-16 14:15:55 +0000227
Sam McCallb324c642019-07-08 18:07:46 +0000228llvm::Optional<std::string>
Kadir Cetinkaya1f6d9842019-07-03 07:47:19 +0000229IncludeInserter::calculateIncludePath(const HeaderFile &InsertedHeader,
230 llvm::StringRef IncludingFile) const {
Eric Liu417c8892019-04-16 14:35:49 +0000231 assert(InsertedHeader.valid());
Eric Liu6c8e8582018-02-26 08:32:13 +0000232 if (InsertedHeader.Verbatim)
233 return InsertedHeader.File;
Eric Liu8f3678d2018-06-15 13:34:18 +0000234 bool IsSystem = false;
Sam McCallb324c642019-07-08 18:07:46 +0000235 std::string Suggested;
236 if (HeaderSearchInfo) {
237 Suggested = HeaderSearchInfo->suggestPathToFileForDiagnostics(
238 InsertedHeader.File, BuildDir, IncludingFile, &IsSystem);
239 } else {
240 // Calculate include relative to including file only.
241 StringRef IncludingDir = llvm::sys::path::parent_path(IncludingFile);
242 SmallString<256> RelFile(InsertedHeader.File);
243 // Replacing with "" leaves "/RelFile" if IncludingDir doesn't end in "/".
244 llvm::sys::path::replace_path_prefix(RelFile, IncludingDir, "./");
245 Suggested = llvm::sys::path::convert_to_slash(
246 llvm::sys::path::remove_leading_dotslash(RelFile));
247 }
248 // FIXME: should we allow (some limited number of) "../header.h"?
249 if (llvm::sys::path::is_absolute(Suggested))
250 return None;
Eric Liuc5105f92018-02-16 14:15:55 +0000251 if (IsSystem)
252 Suggested = "<" + Suggested + ">";
253 else
254 Suggested = "\"" + Suggested + "\"";
Eric Liuc5105f92018-02-16 14:15:55 +0000255 return Suggested;
256}
257
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000258llvm::Optional<TextEdit>
259IncludeInserter::insert(llvm::StringRef VerbatimHeader) const {
260 llvm::Optional<TextEdit> Edit = None;
Eric Liu8f3678d2018-06-15 13:34:18 +0000261 if (auto Insertion = Inserter.insert(VerbatimHeader.trim("\"<>"),
262 VerbatimHeader.startswith("<")))
263 Edit = replacementToEdit(Code, *Insertion);
264 return Edit;
Eric Liu63f419a2018-05-15 15:29:32 +0000265}
266
Sam McCall991e3162018-11-20 10:58:48 +0000267llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const Inclusion &Inc) {
268 return OS << Inc.Written << " = "
Kadir Cetinkayad8700162020-05-04 10:48:19 +0200269 << (!Inc.Resolved.empty() ? Inc.Resolved : "[unresolved]")
270 << " at line" << Inc.HashLine;
Sam McCall991e3162018-11-20 10:58:48 +0000271}
272
Kadir Cetinkaya717bef62020-04-23 17:44:51 +0200273bool operator==(const Inclusion &LHS, const Inclusion &RHS) {
274 return std::tie(LHS.Directive, LHS.FileKind, LHS.HashOffset, LHS.HashLine,
275 LHS.Resolved, LHS.Written) ==
276 std::tie(RHS.Directive, RHS.FileKind, RHS.HashOffset, RHS.HashLine,
277 RHS.Resolved, RHS.Written);
278}
Eric Liuc5105f92018-02-16 14:15:55 +0000279} // namespace clangd
280} // namespace clang