blob: 2ddcd01e6a060a55a5b0d5330891251edd0e7ca7 [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
Ilya Biryukov02d58702017-08-01 15:51:38 +000026class FulfillPromiseGuard {
27public:
28 FulfillPromiseGuard(std::promise<void> &Promise) : Promise(Promise) {}
29
30 ~FulfillPromiseGuard() { Promise.set_value(); }
31
32private:
33 std::promise<void> &Promise;
34};
35
Ilya Biryukovafb55542017-05-16 14:40:30 +000036std::vector<tooling::Replacement> formatCode(StringRef Code, StringRef Filename,
37 ArrayRef<tooling::Range> Ranges) {
38 // Call clang-format.
39 // FIXME: Don't ignore style.
40 format::FormatStyle Style = format::getLLVMStyle();
41 auto Result = format::reformat(Style, Code, Ranges, Filename);
42
43 return std::vector<tooling::Replacement>(Result.begin(), Result.end());
44}
45
Ilya Biryukova46f7a92017-06-28 10:34:50 +000046std::string getStandardResourceDir() {
47 static int Dummy; // Just an address in this process.
48 return CompilerInvocation::GetResourcesPath("clangd", (void *)&Dummy);
49}
50
Ilya Biryukovafb55542017-05-16 14:40:30 +000051} // namespace
52
53size_t clangd::positionToOffset(StringRef Code, Position P) {
54 size_t Offset = 0;
55 for (int I = 0; I != P.line; ++I) {
56 // FIXME: \r\n
57 // FIXME: UTF-8
58 size_t F = Code.find('\n', Offset);
59 if (F == StringRef::npos)
60 return 0; // FIXME: Is this reasonable?
61 Offset = F + 1;
62 }
63 return (Offset == 0 ? 0 : (Offset - 1)) + P.character;
64}
65
66/// Turn an offset in Code into a [line, column] pair.
67Position clangd::offsetToPosition(StringRef Code, size_t Offset) {
68 StringRef JustBefore = Code.substr(0, Offset);
69 // FIXME: \r\n
70 // FIXME: UTF-8
71 int Lines = JustBefore.count('\n');
72 int Cols = JustBefore.size() - JustBefore.rfind('\n') - 1;
73 return {Lines, Cols};
74}
75
Ilya Biryukov22602992017-05-30 15:11:02 +000076Tagged<IntrusiveRefCntPtr<vfs::FileSystem>>
Ilya Biryukovaf0c04b2017-06-14 09:46:44 +000077RealFileSystemProvider::getTaggedFileSystem(PathRef File) {
Ilya Biryukov22602992017-05-30 15:11:02 +000078 return make_tagged(vfs::getRealFileSystem(), VFSTag());
Ilya Biryukov0f62ed22017-05-26 12:26:51 +000079}
80
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +000081unsigned clangd::getDefaultAsyncThreadsCount() {
82 unsigned HardwareConcurrency = std::thread::hardware_concurrency();
83 // C++ standard says that hardware_concurrency()
84 // may return 0, fallback to 1 worker thread in
85 // that case.
86 if (HardwareConcurrency == 0)
87 return 1;
88 return HardwareConcurrency;
89}
90
91ClangdScheduler::ClangdScheduler(unsigned AsyncThreadsCount)
92 : RunSynchronously(AsyncThreadsCount == 0) {
Ilya Biryukov38d79772017-05-16 09:38:59 +000093 if (RunSynchronously) {
94 // Don't start the worker thread if we're running synchronously
95 return;
96 }
97
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +000098 Workers.reserve(AsyncThreadsCount);
99 for (unsigned I = 0; I < AsyncThreadsCount; ++I) {
100 Workers.push_back(std::thread([this]() {
101 while (true) {
102 std::future<void> Request;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000103
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000104 // Pick request from the queue
105 {
106 std::unique_lock<std::mutex> Lock(Mutex);
107 // Wait for more requests.
108 RequestCV.wait(Lock,
109 [this] { return !RequestQueue.empty() || Done; });
110 if (Done)
111 return;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000112
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000113 assert(!RequestQueue.empty() && "RequestQueue was empty");
Ilya Biryukov38d79772017-05-16 09:38:59 +0000114
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000115 // We process requests starting from the front of the queue. Users of
116 // ClangdScheduler have a way to prioritise their requests by putting
117 // them to the either side of the queue (using either addToEnd or
118 // addToFront).
119 Request = std::move(RequestQueue.front());
120 RequestQueue.pop_front();
121 } // unlock Mutex
Ilya Biryukov38d79772017-05-16 09:38:59 +0000122
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000123 Request.get();
124 }
125 }));
126 }
Ilya Biryukov38d79772017-05-16 09:38:59 +0000127}
128
129ClangdScheduler::~ClangdScheduler() {
130 if (RunSynchronously)
131 return; // no worker thread is running in that case
132
133 {
134 std::lock_guard<std::mutex> Lock(Mutex);
135 // Wake up the worker thread
136 Done = true;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000137 } // unlock Mutex
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000138 RequestCV.notify_all();
139
140 for (auto &Worker : Workers)
141 Worker.join();
Ilya Biryukov38d79772017-05-16 09:38:59 +0000142}
143
Ilya Biryukov103c9512017-06-13 15:59:43 +0000144ClangdServer::ClangdServer(GlobalCompilationDatabase &CDB,
145 DiagnosticsConsumer &DiagConsumer,
146 FileSystemProvider &FSProvider,
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000147 unsigned AsyncThreadsCount, bool SnippetCompletions,
Ilya Biryukove5128f72017-09-20 07:24:15 +0000148 clangd::Logger &Logger,
Ilya Biryukova46f7a92017-06-28 10:34:50 +0000149 llvm::Optional<StringRef> ResourceDir)
Ilya Biryukove5128f72017-09-20 07:24:15 +0000150 : Logger(Logger), CDB(CDB), DiagConsumer(DiagConsumer),
151 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 Biryukovb33c1572017-09-12 13:57:14 +0000154 WorkScheduler(AsyncThreadsCount), SnippetCompletions(SnippetCompletions) {
155}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000156
Ilya Biryukov02d58702017-08-01 15:51:38 +0000157std::future<void> ClangdServer::addDocument(PathRef File, StringRef Contents) {
Ilya Biryukovf01af682017-05-23 13:42:59 +0000158 DocVersion Version = DraftMgr.updateDraft(File, Contents);
Ilya Biryukovf01af682017-05-23 13:42:59 +0000159
Ilya Biryukov02d58702017-08-01 15:51:38 +0000160 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
161 std::shared_ptr<CppFile> Resources =
Ilya Biryukove5128f72017-09-20 07:24:15 +0000162 Units.getOrCreateFile(File, ResourceDir, CDB, PCHs, TaggedFS.Value, Logger);
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000163 return scheduleReparseAndDiags(File, VersionedDraft{Version, Contents.str()},
164 std::move(Resources), std::move(TaggedFS));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000165}
166
Ilya Biryukov02d58702017-08-01 15:51:38 +0000167std::future<void> ClangdServer::removeDocument(PathRef File) {
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000168 DraftMgr.removeDraft(File);
169 std::shared_ptr<CppFile> Resources = Units.removeIfPresent(File);
170 return scheduleCancelRebuild(std::move(Resources));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000171}
172
Ilya Biryukov02d58702017-08-01 15:51:38 +0000173std::future<void> ClangdServer::forceReparse(PathRef File) {
Ilya Biryukov91dbf5b2017-08-14 08:37:32 +0000174 auto FileContents = DraftMgr.getDraft(File);
175 assert(FileContents.Draft &&
176 "forceReparse() was called for non-added document");
177
178 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
179 auto Recreated = Units.recreateFileIfCompileCommandChanged(
Ilya Biryukove5128f72017-09-20 07:24:15 +0000180 File, ResourceDir, CDB, PCHs, TaggedFS.Value, Logger);
Ilya Biryukov91dbf5b2017-08-14 08:37:32 +0000181
182 // Note that std::future from this cleanup action is ignored.
183 scheduleCancelRebuild(std::move(Recreated.RemovedFile));
184 // Schedule a reparse.
185 return scheduleReparseAndDiags(File, std::move(FileContents),
186 std::move(Recreated.FileInCollection),
187 std::move(TaggedFS));
Ilya Biryukov0f62ed22017-05-26 12:26:51 +0000188}
189
Ilya Biryukov0e27ce42017-06-13 14:15:56 +0000190Tagged<std::vector<CompletionItem>>
191ClangdServer::codeComplete(PathRef File, Position Pos,
Ilya Biryukoved99e4c2017-07-31 17:09:29 +0000192 llvm::Optional<StringRef> OverridenContents,
193 IntrusiveRefCntPtr<vfs::FileSystem> *UsedFS) {
Ilya Biryukov0e27ce42017-06-13 14:15:56 +0000194 std::string DraftStorage;
195 if (!OverridenContents) {
196 auto FileContents = DraftMgr.getDraft(File);
197 assert(FileContents.Draft &&
198 "codeComplete is called for non-added document");
199
200 DraftStorage = std::move(*FileContents.Draft);
201 OverridenContents = DraftStorage;
202 }
Ilya Biryukov38d79772017-05-16 09:38:59 +0000203
Ilya Biryukovaf0c04b2017-06-14 09:46:44 +0000204 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
Ilya Biryukoved99e4c2017-07-31 17:09:29 +0000205 if (UsedFS)
206 *UsedFS = TaggedFS.Value;
207
Ilya Biryukov02d58702017-08-01 15:51:38 +0000208 std::shared_ptr<CppFile> Resources = Units.getFile(File);
209 assert(Resources && "Calling completion on non-added file");
210
211 auto Preamble = Resources->getPossiblyStalePreamble();
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000212 std::vector<CompletionItem> Result = clangd::codeComplete(
213 File, Resources->getCompileCommand(),
214 Preamble ? &Preamble->Preamble : nullptr, *OverridenContents, Pos,
Ilya Biryukove5128f72017-09-20 07:24:15 +0000215 TaggedFS.Value, PCHs, SnippetCompletions, Logger);
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) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000255 std::shared_ptr<CppFile> Resources = Units.getFile(File);
256 assert(Resources && "dumpAST is called for non-added document");
Ilya Biryukov38d79772017-05-16 09:38:59 +0000257
Ilya Biryukov02d58702017-08-01 15:51:38 +0000258 std::string Result;
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +0000259 Resources->getAST().get()->runUnderLock([&Result](ParsedAST *AST) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000260 llvm::raw_string_ostream ResultOS(Result);
261 if (AST) {
262 clangd::dumpAST(*AST, ResultOS);
263 } else {
264 ResultOS << "<no-ast>";
265 }
266 ResultOS.flush();
Ilya Biryukovf01af682017-05-23 13:42:59 +0000267 });
Ilya Biryukov02d58702017-08-01 15:51:38 +0000268 return Result;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000269}
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000270
Ilya Biryukov02d58702017-08-01 15:51:38 +0000271Tagged<std::vector<Location>> ClangdServer::findDefinitions(PathRef File,
272 Position Pos) {
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000273 auto FileContents = DraftMgr.getDraft(File);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000274 assert(FileContents.Draft &&
275 "findDefinitions is called for non-added document");
276
277 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
278
279 std::shared_ptr<CppFile> Resources = Units.getFile(File);
280 assert(Resources && "Calling findDefinitions on non-added file");
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000281
282 std::vector<Location> Result;
Ilya Biryukove5128f72017-09-20 07:24:15 +0000283 Resources->getAST().get()->runUnderLock([Pos, &Result, this](ParsedAST *AST) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000284 if (!AST)
285 return;
Ilya Biryukove5128f72017-09-20 07:24:15 +0000286 Result = clangd::findDefinitions(*AST, Pos, Logger);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000287 });
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000288 return make_tagged(std::move(Result), TaggedFS.Tag);
289}
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000290
291std::future<void> ClangdServer::scheduleReparseAndDiags(
292 PathRef File, VersionedDraft Contents, std::shared_ptr<CppFile> Resources,
293 Tagged<IntrusiveRefCntPtr<vfs::FileSystem>> TaggedFS) {
294
295 assert(Contents.Draft && "Draft must have contents");
296 std::future<llvm::Optional<std::vector<DiagWithFixIts>>> DeferredRebuild =
297 Resources->deferRebuild(*Contents.Draft, TaggedFS.Value);
298 std::promise<void> DonePromise;
299 std::future<void> DoneFuture = DonePromise.get_future();
300
301 DocVersion Version = Contents.Version;
302 Path FileStr = File;
303 VFSTag Tag = TaggedFS.Tag;
304 auto ReparseAndPublishDiags =
305 [this, FileStr, Version,
306 Tag](std::future<llvm::Optional<std::vector<DiagWithFixIts>>>
307 DeferredRebuild,
308 std::promise<void> DonePromise) -> void {
309 FulfillPromiseGuard Guard(DonePromise);
310
311 auto CurrentVersion = DraftMgr.getVersion(FileStr);
312 if (CurrentVersion != Version)
313 return; // This request is outdated
314
315 auto Diags = DeferredRebuild.get();
316 if (!Diags)
317 return; // A new reparse was requested before this one completed.
318 DiagConsumer.onDiagnosticsReady(FileStr,
319 make_tagged(std::move(*Diags), Tag));
320 };
321
322 WorkScheduler.addToFront(std::move(ReparseAndPublishDiags),
323 std::move(DeferredRebuild), std::move(DonePromise));
324 return DoneFuture;
325}
326
327std::future<void>
328ClangdServer::scheduleCancelRebuild(std::shared_ptr<CppFile> Resources) {
329 std::promise<void> DonePromise;
330 std::future<void> DoneFuture = DonePromise.get_future();
331 if (!Resources) {
332 // No need to schedule any cleanup.
333 DonePromise.set_value();
334 return DoneFuture;
335 }
336
337 std::future<void> DeferredCancel = Resources->deferCancelRebuild();
338 auto CancelReparses = [Resources](std::promise<void> DonePromise,
339 std::future<void> DeferredCancel) {
340 FulfillPromiseGuard Guard(DonePromise);
341 DeferredCancel.get();
342 };
343 WorkScheduler.addToFront(std::move(CancelReparses), std::move(DonePromise),
344 std::move(DeferredCancel));
345 return DoneFuture;
346}