blob: 5e66884622955d3661b1dcb301c1e182419d0080 [file] [log] [blame]
Ilya Biryukov38d79772017-05-16 09:38:59 +00001//===--- ClangdServer.cpp - Main clangd server code --------------*- C++-*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===-------------------------------------------------------------------===//
9
10#include "ClangdServer.h"
Ilya Biryukovafb55542017-05-16 14:40:30 +000011#include "clang/Format/Format.h"
Ilya Biryukov38d79772017-05-16 09:38:59 +000012#include "clang/Frontend/ASTUnit.h"
13#include "clang/Frontend/CompilerInstance.h"
14#include "clang/Frontend/CompilerInvocation.h"
15#include "clang/Tooling/CompilationDatabase.h"
Ilya Biryukovafb55542017-05-16 14:40:30 +000016#include "llvm/ADT/ArrayRef.h"
Ilya Biryukov38d79772017-05-16 09:38:59 +000017#include "llvm/Support/FileSystem.h"
Ilya Biryukovf01af682017-05-23 13:42:59 +000018#include "llvm/Support/raw_ostream.h"
19#include <future>
Ilya Biryukov38d79772017-05-16 09:38:59 +000020
Ilya Biryukov2f314102017-05-16 10:06:20 +000021using namespace clang;
Ilya Biryukov38d79772017-05-16 09:38:59 +000022using namespace clang::clangd;
23
Ilya Biryukovafb55542017-05-16 14:40:30 +000024namespace {
25
26std::vector<tooling::Replacement> formatCode(StringRef Code, StringRef Filename,
27 ArrayRef<tooling::Range> Ranges) {
28 // Call clang-format.
29 // FIXME: Don't ignore style.
30 format::FormatStyle Style = format::getLLVMStyle();
31 auto Result = format::reformat(Style, Code, Ranges, Filename);
32
33 return std::vector<tooling::Replacement>(Result.begin(), Result.end());
34}
35
Ilya Biryukova46f7a92017-06-28 10:34:50 +000036std::string getStandardResourceDir() {
37 static int Dummy; // Just an address in this process.
38 return CompilerInvocation::GetResourcesPath("clangd", (void *)&Dummy);
39}
40
Ilya Biryukovafb55542017-05-16 14:40:30 +000041} // namespace
42
43size_t clangd::positionToOffset(StringRef Code, Position P) {
44 size_t Offset = 0;
45 for (int I = 0; I != P.line; ++I) {
46 // FIXME: \r\n
47 // FIXME: UTF-8
48 size_t F = Code.find('\n', Offset);
49 if (F == StringRef::npos)
50 return 0; // FIXME: Is this reasonable?
51 Offset = F + 1;
52 }
53 return (Offset == 0 ? 0 : (Offset - 1)) + P.character;
54}
55
56/// Turn an offset in Code into a [line, column] pair.
57Position clangd::offsetToPosition(StringRef Code, size_t Offset) {
58 StringRef JustBefore = Code.substr(0, Offset);
59 // FIXME: \r\n
60 // FIXME: UTF-8
61 int Lines = JustBefore.count('\n');
62 int Cols = JustBefore.size() - JustBefore.rfind('\n') - 1;
63 return {Lines, Cols};
64}
65
Ilya Biryukov22602992017-05-30 15:11:02 +000066Tagged<IntrusiveRefCntPtr<vfs::FileSystem>>
Ilya Biryukovaf0c04b2017-06-14 09:46:44 +000067RealFileSystemProvider::getTaggedFileSystem(PathRef File) {
Ilya Biryukov22602992017-05-30 15:11:02 +000068 return make_tagged(vfs::getRealFileSystem(), VFSTag());
Ilya Biryukov0f62ed22017-05-26 12:26:51 +000069}
70
Ilya Biryukovf01af682017-05-23 13:42:59 +000071ClangdScheduler::ClangdScheduler(bool RunSynchronously)
Ilya Biryukov38d79772017-05-16 09:38:59 +000072 : RunSynchronously(RunSynchronously) {
73 if (RunSynchronously) {
74 // Don't start the worker thread if we're running synchronously
75 return;
76 }
77
78 // Initialize Worker in ctor body, rather than init list to avoid potentially
79 // using not-yet-initialized members
Ilya Biryukovf01af682017-05-23 13:42:59 +000080 Worker = std::thread([this]() {
Ilya Biryukov38d79772017-05-16 09:38:59 +000081 while (true) {
Ilya Biryukovf01af682017-05-23 13:42:59 +000082 std::function<void()> Request;
Ilya Biryukov38d79772017-05-16 09:38:59 +000083
84 // Pick request from the queue
85 {
86 std::unique_lock<std::mutex> Lock(Mutex);
87 // Wait for more requests.
88 RequestCV.wait(Lock, [this] { return !RequestQueue.empty() || Done; });
89 if (Done)
90 return;
91
92 assert(!RequestQueue.empty() && "RequestQueue was empty");
93
Ilya Biryukovf01af682017-05-23 13:42:59 +000094 // We process requests starting from the front of the queue. Users of
95 // ClangdScheduler have a way to prioritise their requests by putting
96 // them to the either side of the queue (using either addToEnd or
97 // addToFront).
98 Request = std::move(RequestQueue.front());
99 RequestQueue.pop_front();
Ilya Biryukov38d79772017-05-16 09:38:59 +0000100 } // unlock Mutex
101
Ilya Biryukovf01af682017-05-23 13:42:59 +0000102 Request();
Ilya Biryukov38d79772017-05-16 09:38:59 +0000103 }
104 });
105}
106
107ClangdScheduler::~ClangdScheduler() {
108 if (RunSynchronously)
109 return; // no worker thread is running in that case
110
111 {
112 std::lock_guard<std::mutex> Lock(Mutex);
113 // Wake up the worker thread
114 Done = true;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000115 } // unlock Mutex
Ilya Biryukovf01af682017-05-23 13:42:59 +0000116 RequestCV.notify_one();
Ilya Biryukov38d79772017-05-16 09:38:59 +0000117 Worker.join();
118}
119
Ilya Biryukovf01af682017-05-23 13:42:59 +0000120void ClangdScheduler::addToFront(std::function<void()> Request) {
Ilya Biryukov38d79772017-05-16 09:38:59 +0000121 if (RunSynchronously) {
Ilya Biryukovf01af682017-05-23 13:42:59 +0000122 Request();
Ilya Biryukov38d79772017-05-16 09:38:59 +0000123 return;
124 }
125
Ilya Biryukovf01af682017-05-23 13:42:59 +0000126 {
127 std::lock_guard<std::mutex> Lock(Mutex);
128 RequestQueue.push_front(Request);
129 }
130 RequestCV.notify_one();
131}
132
133void ClangdScheduler::addToEnd(std::function<void()> Request) {
134 if (RunSynchronously) {
135 Request();
136 return;
137 }
138
139 {
140 std::lock_guard<std::mutex> Lock(Mutex);
141 RequestQueue.push_back(Request);
142 }
Ilya Biryukov38d79772017-05-16 09:38:59 +0000143 RequestCV.notify_one();
144}
145
Ilya Biryukov103c9512017-06-13 15:59:43 +0000146ClangdServer::ClangdServer(GlobalCompilationDatabase &CDB,
147 DiagnosticsConsumer &DiagConsumer,
148 FileSystemProvider &FSProvider,
Ilya Biryukova46f7a92017-06-28 10:34:50 +0000149 bool RunSynchronously,
150 llvm::Optional<StringRef> ResourceDir)
Ilya Biryukov103c9512017-06-13 15:59:43 +0000151 : CDB(CDB), DiagConsumer(DiagConsumer), FSProvider(FSProvider),
Ilya Biryukova46f7a92017-06-28 10:34:50 +0000152 ResourceDir(ResourceDir ? ResourceDir->str() : getStandardResourceDir()),
Ilya Biryukov38d79772017-05-16 09:38:59 +0000153 PCHs(std::make_shared<PCHContainerOperations>()),
Ilya Biryukovf01af682017-05-23 13:42:59 +0000154 WorkScheduler(RunSynchronously) {}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000155
156void ClangdServer::addDocument(PathRef File, StringRef Contents) {
Ilya Biryukovf01af682017-05-23 13:42:59 +0000157 DocVersion Version = DraftMgr.updateDraft(File, Contents);
158 Path FileStr = File;
159 WorkScheduler.addToFront([this, FileStr, Version]() {
160 auto FileContents = DraftMgr.getDraft(FileStr);
161 if (FileContents.Version != Version)
162 return; // This request is outdated, do nothing
163
164 assert(FileContents.Draft &&
165 "No contents inside a file that was scheduled for reparse");
Ilya Biryukovaf0c04b2017-06-14 09:46:44 +0000166 auto TaggedFS = FSProvider.getTaggedFileSystem(FileStr);
Ilya Biryukov22602992017-05-30 15:11:02 +0000167 Units.runOnUnit(
Ilya Biryukova46f7a92017-06-28 10:34:50 +0000168 FileStr, *FileContents.Draft, ResourceDir, CDB, PCHs, TaggedFS.Value,
Ilya Biryukov22602992017-05-30 15:11:02 +0000169 [&](ClangdUnit const &Unit) {
Ilya Biryukov103c9512017-06-13 15:59:43 +0000170 DiagConsumer.onDiagnosticsReady(
Ilya Biryukov22602992017-05-30 15:11:02 +0000171 FileStr, make_tagged(Unit.getLocalDiagnostics(), TaggedFS.Tag));
172 });
Ilya Biryukovf01af682017-05-23 13:42:59 +0000173 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000174}
175
176void ClangdServer::removeDocument(PathRef File) {
Ilya Biryukovf01af682017-05-23 13:42:59 +0000177 auto Version = DraftMgr.removeDraft(File);
178 Path FileStr = File;
179 WorkScheduler.addToFront([this, FileStr, Version]() {
180 if (Version != DraftMgr.getVersion(FileStr))
181 return; // This request is outdated, do nothing
182
183 Units.removeUnitIfPresent(FileStr);
184 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000185}
186
Ilya Biryukov0f62ed22017-05-26 12:26:51 +0000187void ClangdServer::forceReparse(PathRef File) {
188 // The addDocument schedules the reparse even if the contents of the file
189 // never changed, so we just call it here.
190 addDocument(File, getDocument(File));
191}
192
Ilya Biryukov0e27ce42017-06-13 14:15:56 +0000193Tagged<std::vector<CompletionItem>>
194ClangdServer::codeComplete(PathRef File, Position Pos,
195 llvm::Optional<StringRef> OverridenContents) {
196 std::string DraftStorage;
197 if (!OverridenContents) {
198 auto FileContents = DraftMgr.getDraft(File);
199 assert(FileContents.Draft &&
200 "codeComplete is called for non-added document");
201
202 DraftStorage = std::move(*FileContents.Draft);
203 OverridenContents = DraftStorage;
204 }
Ilya Biryukov38d79772017-05-16 09:38:59 +0000205
206 std::vector<CompletionItem> Result;
Ilya Biryukovaf0c04b2017-06-14 09:46:44 +0000207 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
Ilya Biryukov0e27ce42017-06-13 14:15:56 +0000208 // It would be nice to use runOnUnitWithoutReparse here, but we can't
209 // guarantee the correctness of code completion cache here if we don't do the
210 // reparse.
Ilya Biryukova46f7a92017-06-28 10:34:50 +0000211 Units.runOnUnit(File, *OverridenContents, ResourceDir, CDB, PCHs,
212 TaggedFS.Value, [&](ClangdUnit &Unit) {
Ilya Biryukov0e27ce42017-06-13 14:15:56 +0000213 Result = Unit.codeComplete(*OverridenContents, Pos,
214 TaggedFS.Value);
215 });
Ilya Biryukov22602992017-05-30 15:11:02 +0000216 return make_tagged(std::move(Result), TaggedFS.Tag);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000217}
Ilya Biryukovf01af682017-05-23 13:42:59 +0000218
Ilya Biryukovafb55542017-05-16 14:40:30 +0000219std::vector<tooling::Replacement> ClangdServer::formatRange(PathRef File,
220 Range Rng) {
221 std::string Code = getDocument(File);
222
223 size_t Begin = positionToOffset(Code, Rng.start);
224 size_t Len = positionToOffset(Code, Rng.end) - Begin;
225 return formatCode(Code, File, {tooling::Range(Begin, Len)});
226}
227
228std::vector<tooling::Replacement> ClangdServer::formatFile(PathRef File) {
229 // Format everything.
230 std::string Code = getDocument(File);
231 return formatCode(Code, File, {tooling::Range(0, Code.size())});
232}
233
234std::vector<tooling::Replacement> ClangdServer::formatOnType(PathRef File,
235 Position Pos) {
236 // Look for the previous opening brace from the character position and
237 // format starting from there.
238 std::string Code = getDocument(File);
239 size_t CursorPos = positionToOffset(Code, Pos);
240 size_t PreviousLBracePos = StringRef(Code).find_last_of('{', CursorPos);
241 if (PreviousLBracePos == StringRef::npos)
242 PreviousLBracePos = CursorPos;
243 size_t Len = 1 + CursorPos - PreviousLBracePos;
244
245 return formatCode(Code, File, {tooling::Range(PreviousLBracePos, Len)});
246}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000247
248std::string ClangdServer::getDocument(PathRef File) {
249 auto draft = DraftMgr.getDraft(File);
250 assert(draft.Draft && "File is not tracked, cannot get contents");
251 return *draft.Draft;
252}
253
Ilya Biryukovf01af682017-05-23 13:42:59 +0000254std::string ClangdServer::dumpAST(PathRef File) {
255 std::promise<std::string> DumpPromise;
256 auto DumpFuture = DumpPromise.get_future();
257 auto Version = DraftMgr.getVersion(File);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000258
Ilya Biryukovf01af682017-05-23 13:42:59 +0000259 WorkScheduler.addToEnd([this, &DumpPromise, File, Version]() {
260 assert(DraftMgr.getVersion(File) == Version && "Version has changed");
Ilya Biryukov38d79772017-05-16 09:38:59 +0000261
Ilya Biryukovf01af682017-05-23 13:42:59 +0000262 Units.runOnExistingUnit(File, [&DumpPromise](ClangdUnit &Unit) {
263 std::string Result;
264
265 llvm::raw_string_ostream ResultOS(Result);
266 Unit.dumpAST(ResultOS);
267 ResultOS.flush();
268
269 DumpPromise.set_value(std::move(Result));
270 });
271 });
272 return DumpFuture.get();
Ilya Biryukov38d79772017-05-16 09:38:59 +0000273}
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000274
275Tagged<std::vector<Location>>
276ClangdServer::findDefinitions(PathRef File, Position Pos) {
277 auto FileContents = DraftMgr.getDraft(File);
278 assert(FileContents.Draft && "findDefinitions is called for non-added document");
279
280 std::vector<Location> Result;
281 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
282 Units.runOnUnit(File, *FileContents.Draft, ResourceDir, CDB, PCHs,
283 TaggedFS.Value, [&](ClangdUnit &Unit) {
284 Result = Unit.findDefinitions(Pos);
285 });
286 return make_tagged(std::move(Result), TaggedFS.Tag);
287}