blob: d4c304fe63bb206d3ec8528ade89d9c14dcbdb17 [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"
Eric Liu709bde82018-02-19 18:48:44 +000017#include "llvm/Support/Path.h"
Eric Liuc5105f92018-02-16 14:15:55 +000018
19namespace clang {
20namespace clangd {
21namespace {
22
23class RecordHeaders : public PPCallbacks {
24public:
Sam McCall3f0243f2018-07-03 08:09:29 +000025 RecordHeaders(const SourceManager &SM, IncludeStructure *Out)
26 : SM(SM), Out(Out) {}
Eric Liuc5105f92018-02-16 14:15:55 +000027
Eric Liu155f5a42018-05-14 12:19:16 +000028 // Record existing #includes - both written and resolved paths. Only #includes
29 // in the main file are collected.
30 void InclusionDirective(SourceLocation HashLoc, const Token & /*IncludeTok*/,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000031 llvm::StringRef FileName, bool IsAngled,
Eric Liu155f5a42018-05-14 12:19:16 +000032 CharSourceRange FilenameRange, const FileEntry *File,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000033 llvm::StringRef /*SearchPath*/,
34 llvm::StringRef /*RelativePath*/,
Julie Hockett546943f2018-05-10 19:13:14 +000035 const Module * /*Imported*/,
Sam McCall991e3162018-11-20 10:58:48 +000036 SrcMgr::CharacteristicKind FileKind) override {
37 if (SM.isWrittenInMainFile(HashLoc)) {
38 Out->MainFileIncludes.emplace_back();
39 auto &Inc = Out->MainFileIncludes.back();
40 Inc.R = halfOpenToRange(SM, FilenameRange);
41 Inc.Written =
42 (IsAngled ? "<" + FileName + ">" : "\"" + FileName + "\"").str();
43 Inc.Resolved = File ? File->tryGetRealPathName() : "";
44 Inc.HashOffset = SM.getFileOffset(HashLoc);
45 Inc.FileKind = FileKind;
46 }
Sam McCall3f0243f2018-07-03 08:09:29 +000047 if (File) {
48 auto *IncludingFileEntry = SM.getFileEntryForID(SM.getFileID(HashLoc));
49 if (!IncludingFileEntry) {
50 assert(SM.getBufferName(HashLoc).startswith("<") &&
51 "Expected #include location to be a file or <built-in>");
52 // Treat as if included from the main file.
53 IncludingFileEntry = SM.getFileEntryForID(SM.getMainFileID());
54 }
55 Out->recordInclude(IncludingFileEntry->getName(), File->getName(),
56 File->tryGetRealPathName());
57 }
Eric Liuc5105f92018-02-16 14:15:55 +000058 }
59
60private:
Eric Liu155f5a42018-05-14 12:19:16 +000061 const SourceManager &SM;
Sam McCall3f0243f2018-07-03 08:09:29 +000062 IncludeStructure *Out;
Eric Liuc5105f92018-02-16 14:15:55 +000063};
64
65} // namespace
66
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000067bool isLiteralInclude(llvm::StringRef Include) {
Eric Liu6c8e8582018-02-26 08:32:13 +000068 return Include.startswith("<") || Include.startswith("\"");
69}
70
71bool HeaderFile::valid() const {
72 return (Verbatim && isLiteralInclude(File)) ||
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000073 (!Verbatim && llvm::sys::path::is_absolute(File));
Eric Liu6c8e8582018-02-26 08:32:13 +000074}
75
Eric Liudd662772019-01-28 14:01:55 +000076llvm::Expected<HeaderFile> toHeaderFile(llvm::StringRef Header,
77 llvm::StringRef HintPath) {
78 if (isLiteralInclude(Header))
79 return HeaderFile{Header.str(), /*Verbatim=*/true};
80 auto U = URI::parse(Header);
81 if (!U)
82 return U.takeError();
83
84 auto IncludePath = URI::includeSpelling(*U);
85 if (!IncludePath)
86 return IncludePath.takeError();
87 if (!IncludePath->empty())
88 return HeaderFile{std::move(*IncludePath), /*Verbatim=*/true};
89
90 auto Resolved = URI::resolve(*U, HintPath);
91 if (!Resolved)
92 return Resolved.takeError();
93 return HeaderFile{std::move(*Resolved), /*Verbatim=*/false};
94}
95
96llvm::SmallVector<llvm::StringRef, 1> getRankedIncludes(const Symbol &Sym) {
97 auto Includes = Sym.IncludeHeaders;
98 // Sort in descending order by reference count and header length.
99 llvm::sort(Includes, [](const Symbol::IncludeHeaderWithReferences &LHS,
100 const Symbol::IncludeHeaderWithReferences &RHS) {
101 if (LHS.References == RHS.References)
102 return LHS.IncludeHeader.size() < RHS.IncludeHeader.size();
103 return LHS.References > RHS.References;
104 });
105 llvm::SmallVector<llvm::StringRef, 1> Headers;
106 for (const auto &Include : Includes)
107 Headers.push_back(Include.IncludeHeader);
108 return Headers;
109}
110
Eric Liu155f5a42018-05-14 12:19:16 +0000111std::unique_ptr<PPCallbacks>
Sam McCall3f0243f2018-07-03 08:09:29 +0000112collectIncludeStructureCallback(const SourceManager &SM,
113 IncludeStructure *Out) {
114 return llvm::make_unique<RecordHeaders>(SM, Out);
115}
116
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000117void IncludeStructure::recordInclude(llvm::StringRef IncludingName,
118 llvm::StringRef IncludedName,
119 llvm::StringRef IncludedRealName) {
Sam McCall3f0243f2018-07-03 08:09:29 +0000120 auto Child = fileIndex(IncludedName);
121 if (!IncludedRealName.empty() && RealPathNames[Child].empty())
122 RealPathNames[Child] = IncludedRealName;
123 auto Parent = fileIndex(IncludingName);
124 IncludeChildren[Parent].push_back(Child);
125}
126
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000127unsigned IncludeStructure::fileIndex(llvm::StringRef Name) {
Sam McCall3f0243f2018-07-03 08:09:29 +0000128 auto R = NameToIndex.try_emplace(Name, RealPathNames.size());
129 if (R.second)
130 RealPathNames.emplace_back();
131 return R.first->getValue();
132}
133
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000134llvm::StringMap<unsigned>
135IncludeStructure::includeDepth(llvm::StringRef Root) const {
Sam McCall3f0243f2018-07-03 08:09:29 +0000136 // Include depth 0 is the main file only.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000137 llvm::StringMap<unsigned> Result;
Sam McCall3f0243f2018-07-03 08:09:29 +0000138 Result[Root] = 0;
139 std::vector<unsigned> CurrentLevel;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000140 llvm::DenseSet<unsigned> Seen;
Sam McCall3f0243f2018-07-03 08:09:29 +0000141 auto It = NameToIndex.find(Root);
142 if (It != NameToIndex.end()) {
143 CurrentLevel.push_back(It->second);
144 Seen.insert(It->second);
145 }
146
147 // Each round of BFS traversal finds the next depth level.
148 std::vector<unsigned> PreviousLevel;
149 for (unsigned Level = 1; !CurrentLevel.empty(); ++Level) {
150 PreviousLevel.clear();
151 PreviousLevel.swap(CurrentLevel);
152 for (const auto &Parent : PreviousLevel) {
153 for (const auto &Child : IncludeChildren.lookup(Parent)) {
154 if (Seen.insert(Child).second) {
155 CurrentLevel.push_back(Child);
156 const auto &Name = RealPathNames[Child];
157 // Can't include files if we don't have their real path.
158 if (!Name.empty())
159 Result[Name] = Level;
160 }
161 }
162 }
163 }
164 return Result;
Eric Liu155f5a42018-05-14 12:19:16 +0000165}
166
Eric Liufd9f4262018-09-27 14:27:02 +0000167void IncludeInserter::addExisting(const Inclusion &Inc) {
168 IncludedHeaders.insert(Inc.Written);
169 if (!Inc.Resolved.empty())
170 IncludedHeaders.insert(Inc.Resolved);
171}
172
Eric Liuc5105f92018-02-16 14:15:55 +0000173/// FIXME(ioeric): we might not want to insert an absolute include path if the
174/// path is not shortened.
Eric Liu8f3678d2018-06-15 13:34:18 +0000175bool IncludeInserter::shouldInsertInclude(
176 const HeaderFile &DeclaringHeader, const HeaderFile &InsertedHeader) const {
Eric Liu6c8e8582018-02-26 08:32:13 +0000177 assert(DeclaringHeader.valid() && InsertedHeader.valid());
Eric Liu00d99bd2019-04-11 09:36:36 +0000178 if (!HeaderSearchInfo && !InsertedHeader.Verbatim)
179 return false;
Eric Liu8f3678d2018-06-15 13:34:18 +0000180 if (FileName == DeclaringHeader.File || FileName == InsertedHeader.File)
181 return false;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000182 auto Included = [&](llvm::StringRef Header) {
Eric Liu155f5a42018-05-14 12:19:16 +0000183 return IncludedHeaders.find(Header) != IncludedHeaders.end();
Eric Liu6c8e8582018-02-26 08:32:13 +0000184 };
Eric Liu8f3678d2018-06-15 13:34:18 +0000185 return !Included(DeclaringHeader.File) && !Included(InsertedHeader.File);
186}
Eric Liuc5105f92018-02-16 14:15:55 +0000187
Eric Liu8f3678d2018-06-15 13:34:18 +0000188std::string
189IncludeInserter::calculateIncludePath(const HeaderFile &DeclaringHeader,
190 const HeaderFile &InsertedHeader) const {
191 assert(DeclaringHeader.valid() && InsertedHeader.valid());
Eric Liu6c8e8582018-02-26 08:32:13 +0000192 if (InsertedHeader.Verbatim)
193 return InsertedHeader.File;
Eric Liu8f3678d2018-06-15 13:34:18 +0000194 bool IsSystem = false;
Eric Liu00d99bd2019-04-11 09:36:36 +0000195 if (!HeaderSearchInfo)
196 return "\"" + InsertedHeader.File + "\"";
197 std::string Suggested = HeaderSearchInfo->suggestPathToFileForDiagnostics(
Eric Liu63f419a2018-05-15 15:29:32 +0000198 InsertedHeader.File, BuildDir, &IsSystem);
Eric Liuc5105f92018-02-16 14:15:55 +0000199 if (IsSystem)
200 Suggested = "<" + Suggested + ">";
201 else
202 Suggested = "\"" + Suggested + "\"";
Eric Liuc5105f92018-02-16 14:15:55 +0000203 return Suggested;
204}
205
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000206llvm::Optional<TextEdit>
207IncludeInserter::insert(llvm::StringRef VerbatimHeader) const {
208 llvm::Optional<TextEdit> Edit = None;
Eric Liu8f3678d2018-06-15 13:34:18 +0000209 if (auto Insertion = Inserter.insert(VerbatimHeader.trim("\"<>"),
210 VerbatimHeader.startswith("<")))
211 Edit = replacementToEdit(Code, *Insertion);
212 return Edit;
Eric Liu63f419a2018-05-15 15:29:32 +0000213}
214
Sam McCall991e3162018-11-20 10:58:48 +0000215llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const Inclusion &Inc) {
216 return OS << Inc.Written << " = "
217 << (Inc.Resolved.empty() ? Inc.Resolved : "[unresolved]") << " at "
218 << Inc.R;
219}
220
Eric Liuc5105f92018-02-16 14:15:55 +0000221} // namespace clangd
222} // namespace clang