blob: dd4cafd2ddfc263b3705c1f8e783a014c30daf31 [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"
11#include "Logger.h"
Eric Liu155f5a42018-05-14 12:19:16 +000012#include "SourceCode.h"
Eric Liuc5105f92018-02-16 14:15:55 +000013#include "clang/Frontend/CompilerInstance.h"
14#include "clang/Frontend/CompilerInvocation.h"
15#include "clang/Frontend/FrontendActions.h"
16#include "clang/Lex/HeaderSearch.h"
Kadir Cetinkaya1f6d9842019-07-03 07:47:19 +000017#include "llvm/ADT/StringRef.h"
Eric Liu709bde82018-02-19 18:48:44 +000018#include "llvm/Support/Path.h"
Eric Liuc5105f92018-02-16 14:15:55 +000019
20namespace clang {
21namespace clangd {
22namespace {
23
24class RecordHeaders : public PPCallbacks {
25public:
Sam McCall3f0243f2018-07-03 08:09:29 +000026 RecordHeaders(const SourceManager &SM, IncludeStructure *Out)
27 : SM(SM), Out(Out) {}
Eric Liuc5105f92018-02-16 14:15:55 +000028
Eric Liu155f5a42018-05-14 12:19:16 +000029 // Record existing #includes - both written and resolved paths. Only #includes
30 // in the main file are collected.
Kadir Cetinkaya6e017182020-04-15 22:00:19 +020031 void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000032 llvm::StringRef FileName, bool IsAngled,
Eric Liu155f5a42018-05-14 12:19:16 +000033 CharSourceRange FilenameRange, const FileEntry *File,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000034 llvm::StringRef /*SearchPath*/,
35 llvm::StringRef /*RelativePath*/,
Julie Hockett546943f2018-05-10 19:13:14 +000036 const Module * /*Imported*/,
Sam McCall991e3162018-11-20 10:58:48 +000037 SrcMgr::CharacteristicKind FileKind) override {
Haojian Wu6ae86ea2019-07-19 08:33:39 +000038 if (isInsideMainFile(HashLoc, SM)) {
Sam McCall991e3162018-11-20 10:58:48 +000039 Out->MainFileIncludes.emplace_back();
40 auto &Inc = Out->MainFileIncludes.back();
41 Inc.R = halfOpenToRange(SM, FilenameRange);
42 Inc.Written =
43 (IsAngled ? "<" + FileName + ">" : "\"" + FileName + "\"").str();
Benjamin Krameradcd0262020-01-28 20:23:46 +010044 Inc.Resolved = std::string(File ? File->tryGetRealPathName() : "");
Sam McCall991e3162018-11-20 10:58:48 +000045 Inc.HashOffset = SM.getFileOffset(HashLoc);
46 Inc.FileKind = FileKind;
Kadir Cetinkaya6e017182020-04-15 22:00:19 +020047 Inc.Directive = IncludeTok.getIdentifierInfo()->getPPKeywordID();
Sam McCall991e3162018-11-20 10:58:48 +000048 }
Sam McCall3f0243f2018-07-03 08:09:29 +000049 if (File) {
50 auto *IncludingFileEntry = SM.getFileEntryForID(SM.getFileID(HashLoc));
51 if (!IncludingFileEntry) {
52 assert(SM.getBufferName(HashLoc).startswith("<") &&
53 "Expected #include location to be a file or <built-in>");
54 // Treat as if included from the main file.
55 IncludingFileEntry = SM.getFileEntryForID(SM.getMainFileID());
56 }
57 Out->recordInclude(IncludingFileEntry->getName(), File->getName(),
58 File->tryGetRealPathName());
59 }
Eric Liuc5105f92018-02-16 14:15:55 +000060 }
61
62private:
Eric Liu155f5a42018-05-14 12:19:16 +000063 const SourceManager &SM;
Sam McCall3f0243f2018-07-03 08:09:29 +000064 IncludeStructure *Out;
Eric Liuc5105f92018-02-16 14:15:55 +000065};
66
67} // namespace
68
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000069bool isLiteralInclude(llvm::StringRef Include) {
Eric Liu6c8e8582018-02-26 08:32:13 +000070 return Include.startswith("<") || Include.startswith("\"");
71}
72
73bool HeaderFile::valid() const {
74 return (Verbatim && isLiteralInclude(File)) ||
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000075 (!Verbatim && llvm::sys::path::is_absolute(File));
Eric Liu6c8e8582018-02-26 08:32:13 +000076}
77
Eric Liudd662772019-01-28 14:01:55 +000078llvm::Expected<HeaderFile> toHeaderFile(llvm::StringRef Header,
79 llvm::StringRef HintPath) {
80 if (isLiteralInclude(Header))
81 return HeaderFile{Header.str(), /*Verbatim=*/true};
82 auto U = URI::parse(Header);
83 if (!U)
84 return U.takeError();
85
86 auto IncludePath = URI::includeSpelling(*U);
87 if (!IncludePath)
88 return IncludePath.takeError();
89 if (!IncludePath->empty())
90 return HeaderFile{std::move(*IncludePath), /*Verbatim=*/true};
91
92 auto Resolved = URI::resolve(*U, HintPath);
93 if (!Resolved)
94 return Resolved.takeError();
95 return HeaderFile{std::move(*Resolved), /*Verbatim=*/false};
96}
97
98llvm::SmallVector<llvm::StringRef, 1> getRankedIncludes(const Symbol &Sym) {
99 auto Includes = Sym.IncludeHeaders;
100 // Sort in descending order by reference count and header length.
101 llvm::sort(Includes, [](const Symbol::IncludeHeaderWithReferences &LHS,
102 const Symbol::IncludeHeaderWithReferences &RHS) {
103 if (LHS.References == RHS.References)
104 return LHS.IncludeHeader.size() < RHS.IncludeHeader.size();
105 return LHS.References > RHS.References;
106 });
107 llvm::SmallVector<llvm::StringRef, 1> Headers;
108 for (const auto &Include : Includes)
109 Headers.push_back(Include.IncludeHeader);
110 return Headers;
111}
112
Eric Liu155f5a42018-05-14 12:19:16 +0000113std::unique_ptr<PPCallbacks>
Sam McCall3f0243f2018-07-03 08:09:29 +0000114collectIncludeStructureCallback(const SourceManager &SM,
115 IncludeStructure *Out) {
Jonas Devlieghere1c705d92019-08-14 23:52:23 +0000116 return std::make_unique<RecordHeaders>(SM, Out);
Sam McCall3f0243f2018-07-03 08:09:29 +0000117}
118
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000119void IncludeStructure::recordInclude(llvm::StringRef IncludingName,
120 llvm::StringRef IncludedName,
121 llvm::StringRef IncludedRealName) {
Sam McCall3f0243f2018-07-03 08:09:29 +0000122 auto Child = fileIndex(IncludedName);
123 if (!IncludedRealName.empty() && RealPathNames[Child].empty())
Benjamin Krameradcd0262020-01-28 20:23:46 +0100124 RealPathNames[Child] = std::string(IncludedRealName);
Sam McCall3f0243f2018-07-03 08:09:29 +0000125 auto Parent = fileIndex(IncludingName);
126 IncludeChildren[Parent].push_back(Child);
127}
128
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000129unsigned IncludeStructure::fileIndex(llvm::StringRef Name) {
Sam McCall3f0243f2018-07-03 08:09:29 +0000130 auto R = NameToIndex.try_emplace(Name, RealPathNames.size());
131 if (R.second)
132 RealPathNames.emplace_back();
133 return R.first->getValue();
134}
135
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000136llvm::StringMap<unsigned>
137IncludeStructure::includeDepth(llvm::StringRef Root) const {
Sam McCall3f0243f2018-07-03 08:09:29 +0000138 // Include depth 0 is the main file only.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000139 llvm::StringMap<unsigned> Result;
Sam McCall3f0243f2018-07-03 08:09:29 +0000140 Result[Root] = 0;
141 std::vector<unsigned> CurrentLevel;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000142 llvm::DenseSet<unsigned> Seen;
Sam McCall3f0243f2018-07-03 08:09:29 +0000143 auto It = NameToIndex.find(Root);
144 if (It != NameToIndex.end()) {
145 CurrentLevel.push_back(It->second);
146 Seen.insert(It->second);
147 }
148
149 // Each round of BFS traversal finds the next depth level.
150 std::vector<unsigned> PreviousLevel;
151 for (unsigned Level = 1; !CurrentLevel.empty(); ++Level) {
152 PreviousLevel.clear();
153 PreviousLevel.swap(CurrentLevel);
154 for (const auto &Parent : PreviousLevel) {
155 for (const auto &Child : IncludeChildren.lookup(Parent)) {
156 if (Seen.insert(Child).second) {
157 CurrentLevel.push_back(Child);
158 const auto &Name = RealPathNames[Child];
159 // Can't include files if we don't have their real path.
160 if (!Name.empty())
161 Result[Name] = Level;
162 }
163 }
164 }
165 }
166 return Result;
Eric Liu155f5a42018-05-14 12:19:16 +0000167}
168
Eric Liufd9f4262018-09-27 14:27:02 +0000169void IncludeInserter::addExisting(const Inclusion &Inc) {
170 IncludedHeaders.insert(Inc.Written);
171 if (!Inc.Resolved.empty())
172 IncludedHeaders.insert(Inc.Resolved);
173}
174
Eric Liuc5105f92018-02-16 14:15:55 +0000175/// FIXME(ioeric): we might not want to insert an absolute include path if the
176/// path is not shortened.
Eric Liu8f3678d2018-06-15 13:34:18 +0000177bool IncludeInserter::shouldInsertInclude(
Eric Liu417c8892019-04-16 14:35:49 +0000178 PathRef DeclaringHeader, const HeaderFile &InsertedHeader) const {
179 assert(InsertedHeader.valid());
Eric Liu00d99bd2019-04-11 09:36:36 +0000180 if (!HeaderSearchInfo && !InsertedHeader.Verbatim)
181 return false;
Eric Liu417c8892019-04-16 14:35:49 +0000182 if (FileName == DeclaringHeader || FileName == InsertedHeader.File)
Eric Liu8f3678d2018-06-15 13:34:18 +0000183 return false;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000184 auto Included = [&](llvm::StringRef Header) {
Eric Liu155f5a42018-05-14 12:19:16 +0000185 return IncludedHeaders.find(Header) != IncludedHeaders.end();
Eric Liu6c8e8582018-02-26 08:32:13 +0000186 };
Eric Liu417c8892019-04-16 14:35:49 +0000187 return !Included(DeclaringHeader) && !Included(InsertedHeader.File);
Eric Liu8f3678d2018-06-15 13:34:18 +0000188}
Eric Liuc5105f92018-02-16 14:15:55 +0000189
Sam McCallb324c642019-07-08 18:07:46 +0000190llvm::Optional<std::string>
Kadir Cetinkaya1f6d9842019-07-03 07:47:19 +0000191IncludeInserter::calculateIncludePath(const HeaderFile &InsertedHeader,
192 llvm::StringRef IncludingFile) const {
Eric Liu417c8892019-04-16 14:35:49 +0000193 assert(InsertedHeader.valid());
Eric Liu6c8e8582018-02-26 08:32:13 +0000194 if (InsertedHeader.Verbatim)
195 return InsertedHeader.File;
Eric Liu8f3678d2018-06-15 13:34:18 +0000196 bool IsSystem = false;
Sam McCallb324c642019-07-08 18:07:46 +0000197 std::string Suggested;
198 if (HeaderSearchInfo) {
199 Suggested = HeaderSearchInfo->suggestPathToFileForDiagnostics(
200 InsertedHeader.File, BuildDir, IncludingFile, &IsSystem);
201 } else {
202 // Calculate include relative to including file only.
203 StringRef IncludingDir = llvm::sys::path::parent_path(IncludingFile);
204 SmallString<256> RelFile(InsertedHeader.File);
205 // Replacing with "" leaves "/RelFile" if IncludingDir doesn't end in "/".
206 llvm::sys::path::replace_path_prefix(RelFile, IncludingDir, "./");
207 Suggested = llvm::sys::path::convert_to_slash(
208 llvm::sys::path::remove_leading_dotslash(RelFile));
209 }
210 // FIXME: should we allow (some limited number of) "../header.h"?
211 if (llvm::sys::path::is_absolute(Suggested))
212 return None;
Eric Liuc5105f92018-02-16 14:15:55 +0000213 if (IsSystem)
214 Suggested = "<" + Suggested + ">";
215 else
216 Suggested = "\"" + Suggested + "\"";
Eric Liuc5105f92018-02-16 14:15:55 +0000217 return Suggested;
218}
219
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000220llvm::Optional<TextEdit>
221IncludeInserter::insert(llvm::StringRef VerbatimHeader) const {
222 llvm::Optional<TextEdit> Edit = None;
Eric Liu8f3678d2018-06-15 13:34:18 +0000223 if (auto Insertion = Inserter.insert(VerbatimHeader.trim("\"<>"),
224 VerbatimHeader.startswith("<")))
225 Edit = replacementToEdit(Code, *Insertion);
226 return Edit;
Eric Liu63f419a2018-05-15 15:29:32 +0000227}
228
Sam McCall991e3162018-11-20 10:58:48 +0000229llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const Inclusion &Inc) {
230 return OS << Inc.Written << " = "
Kadir Cetinkaya59c28102020-04-07 13:47:51 +0200231 << (!Inc.Resolved.empty() ? Inc.Resolved : "[unresolved]") << " at "
Sam McCall991e3162018-11-20 10:58:48 +0000232 << Inc.R;
233}
234
Eric Liuc5105f92018-02-16 14:15:55 +0000235} // namespace clangd
236} // namespace clang