blob: 5d4a74a4d0354aa8d4d0380df6fd7616adb56576 [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 Biryukova46f7a92017-06-28 10:34:50 +0000148 llvm::Optional<StringRef> ResourceDir)
Ilya Biryukov103c9512017-06-13 15:59:43 +0000149 : CDB(CDB), DiagConsumer(DiagConsumer), FSProvider(FSProvider),
Ilya Biryukova46f7a92017-06-28 10:34:50 +0000150 ResourceDir(ResourceDir ? ResourceDir->str() : getStandardResourceDir()),
Ilya Biryukov38d79772017-05-16 09:38:59 +0000151 PCHs(std::make_shared<PCHContainerOperations>()),
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000152 WorkScheduler(AsyncThreadsCount), SnippetCompletions(SnippetCompletions) {
153}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000154
Ilya Biryukov02d58702017-08-01 15:51:38 +0000155std::future<void> ClangdServer::addDocument(PathRef File, StringRef Contents) {
Ilya Biryukovf01af682017-05-23 13:42:59 +0000156 DocVersion Version = DraftMgr.updateDraft(File, Contents);
Ilya Biryukovf01af682017-05-23 13:42:59 +0000157
Ilya Biryukov02d58702017-08-01 15:51:38 +0000158 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
159 std::shared_ptr<CppFile> Resources =
160 Units.getOrCreateFile(File, ResourceDir, CDB, PCHs, TaggedFS.Value);
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000161 return scheduleReparseAndDiags(File, VersionedDraft{Version, Contents.str()},
162 std::move(Resources), std::move(TaggedFS));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000163}
164
Ilya Biryukov02d58702017-08-01 15:51:38 +0000165std::future<void> ClangdServer::removeDocument(PathRef File) {
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000166 DraftMgr.removeDraft(File);
167 std::shared_ptr<CppFile> Resources = Units.removeIfPresent(File);
168 return scheduleCancelRebuild(std::move(Resources));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000169}
170
Ilya Biryukov02d58702017-08-01 15:51:38 +0000171std::future<void> ClangdServer::forceReparse(PathRef File) {
Ilya Biryukov91dbf5b2017-08-14 08:37:32 +0000172 auto FileContents = DraftMgr.getDraft(File);
173 assert(FileContents.Draft &&
174 "forceReparse() was called for non-added document");
175
176 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
177 auto Recreated = Units.recreateFileIfCompileCommandChanged(
178 File, ResourceDir, CDB, PCHs, TaggedFS.Value);
179
180 // Note that std::future from this cleanup action is ignored.
181 scheduleCancelRebuild(std::move(Recreated.RemovedFile));
182 // Schedule a reparse.
183 return scheduleReparseAndDiags(File, std::move(FileContents),
184 std::move(Recreated.FileInCollection),
185 std::move(TaggedFS));
Ilya Biryukov0f62ed22017-05-26 12:26:51 +0000186}
187
Ilya Biryukov0e27ce42017-06-13 14:15:56 +0000188Tagged<std::vector<CompletionItem>>
189ClangdServer::codeComplete(PathRef File, Position Pos,
Ilya Biryukoved99e4c2017-07-31 17:09:29 +0000190 llvm::Optional<StringRef> OverridenContents,
191 IntrusiveRefCntPtr<vfs::FileSystem> *UsedFS) {
Ilya Biryukov0e27ce42017-06-13 14:15:56 +0000192 std::string DraftStorage;
193 if (!OverridenContents) {
194 auto FileContents = DraftMgr.getDraft(File);
195 assert(FileContents.Draft &&
196 "codeComplete is called for non-added document");
197
198 DraftStorage = std::move(*FileContents.Draft);
199 OverridenContents = DraftStorage;
200 }
Ilya Biryukov38d79772017-05-16 09:38:59 +0000201
Ilya Biryukovaf0c04b2017-06-14 09:46:44 +0000202 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
Ilya Biryukoved99e4c2017-07-31 17:09:29 +0000203 if (UsedFS)
204 *UsedFS = TaggedFS.Value;
205
Ilya Biryukov02d58702017-08-01 15:51:38 +0000206 std::shared_ptr<CppFile> Resources = Units.getFile(File);
207 assert(Resources && "Calling completion on non-added file");
208
209 auto Preamble = Resources->getPossiblyStalePreamble();
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000210 std::vector<CompletionItem> Result = clangd::codeComplete(
211 File, Resources->getCompileCommand(),
212 Preamble ? &Preamble->Preamble : nullptr, *OverridenContents, Pos,
213 TaggedFS.Value, PCHs, SnippetCompletions);
Ilya Biryukov22602992017-05-30 15:11:02 +0000214 return make_tagged(std::move(Result), TaggedFS.Tag);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000215}
Ilya Biryukovf01af682017-05-23 13:42:59 +0000216
Ilya Biryukovafb55542017-05-16 14:40:30 +0000217std::vector<tooling::Replacement> ClangdServer::formatRange(PathRef File,
218 Range Rng) {
219 std::string Code = getDocument(File);
220
221 size_t Begin = positionToOffset(Code, Rng.start);
222 size_t Len = positionToOffset(Code, Rng.end) - Begin;
223 return formatCode(Code, File, {tooling::Range(Begin, Len)});
224}
225
226std::vector<tooling::Replacement> ClangdServer::formatFile(PathRef File) {
227 // Format everything.
228 std::string Code = getDocument(File);
229 return formatCode(Code, File, {tooling::Range(0, Code.size())});
230}
231
232std::vector<tooling::Replacement> ClangdServer::formatOnType(PathRef File,
233 Position Pos) {
234 // Look for the previous opening brace from the character position and
235 // format starting from there.
236 std::string Code = getDocument(File);
237 size_t CursorPos = positionToOffset(Code, Pos);
238 size_t PreviousLBracePos = StringRef(Code).find_last_of('{', CursorPos);
239 if (PreviousLBracePos == StringRef::npos)
240 PreviousLBracePos = CursorPos;
241 size_t Len = 1 + CursorPos - PreviousLBracePos;
242
243 return formatCode(Code, File, {tooling::Range(PreviousLBracePos, Len)});
244}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000245
246std::string ClangdServer::getDocument(PathRef File) {
247 auto draft = DraftMgr.getDraft(File);
248 assert(draft.Draft && "File is not tracked, cannot get contents");
249 return *draft.Draft;
250}
251
Ilya Biryukovf01af682017-05-23 13:42:59 +0000252std::string ClangdServer::dumpAST(PathRef File) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000253 std::shared_ptr<CppFile> Resources = Units.getFile(File);
254 assert(Resources && "dumpAST is called for non-added document");
Ilya Biryukov38d79772017-05-16 09:38:59 +0000255
Ilya Biryukov02d58702017-08-01 15:51:38 +0000256 std::string Result;
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +0000257 Resources->getAST().get()->runUnderLock([&Result](ParsedAST *AST) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000258 llvm::raw_string_ostream ResultOS(Result);
259 if (AST) {
260 clangd::dumpAST(*AST, ResultOS);
261 } else {
262 ResultOS << "<no-ast>";
263 }
264 ResultOS.flush();
Ilya Biryukovf01af682017-05-23 13:42:59 +0000265 });
Ilya Biryukov02d58702017-08-01 15:51:38 +0000266 return Result;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000267}
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000268
Ilya Biryukov02d58702017-08-01 15:51:38 +0000269Tagged<std::vector<Location>> ClangdServer::findDefinitions(PathRef File,
270 Position Pos) {
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000271 auto FileContents = DraftMgr.getDraft(File);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000272 assert(FileContents.Draft &&
273 "findDefinitions is called for non-added document");
274
275 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
276
277 std::shared_ptr<CppFile> Resources = Units.getFile(File);
278 assert(Resources && "Calling findDefinitions on non-added file");
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000279
280 std::vector<Location> Result;
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +0000281 Resources->getAST().get()->runUnderLock([Pos, &Result](ParsedAST *AST) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000282 if (!AST)
283 return;
284 Result = clangd::findDefinitions(*AST, Pos);
285 });
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000286 return make_tagged(std::move(Result), TaggedFS.Tag);
287}
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000288
289std::future<void> ClangdServer::scheduleReparseAndDiags(
290 PathRef File, VersionedDraft Contents, std::shared_ptr<CppFile> Resources,
291 Tagged<IntrusiveRefCntPtr<vfs::FileSystem>> TaggedFS) {
292
293 assert(Contents.Draft && "Draft must have contents");
294 std::future<llvm::Optional<std::vector<DiagWithFixIts>>> DeferredRebuild =
295 Resources->deferRebuild(*Contents.Draft, TaggedFS.Value);
296 std::promise<void> DonePromise;
297 std::future<void> DoneFuture = DonePromise.get_future();
298
299 DocVersion Version = Contents.Version;
300 Path FileStr = File;
301 VFSTag Tag = TaggedFS.Tag;
302 auto ReparseAndPublishDiags =
303 [this, FileStr, Version,
304 Tag](std::future<llvm::Optional<std::vector<DiagWithFixIts>>>
305 DeferredRebuild,
306 std::promise<void> DonePromise) -> void {
307 FulfillPromiseGuard Guard(DonePromise);
308
309 auto CurrentVersion = DraftMgr.getVersion(FileStr);
310 if (CurrentVersion != Version)
311 return; // This request is outdated
312
313 auto Diags = DeferredRebuild.get();
314 if (!Diags)
315 return; // A new reparse was requested before this one completed.
316 DiagConsumer.onDiagnosticsReady(FileStr,
317 make_tagged(std::move(*Diags), Tag));
318 };
319
320 WorkScheduler.addToFront(std::move(ReparseAndPublishDiags),
321 std::move(DeferredRebuild), std::move(DonePromise));
322 return DoneFuture;
323}
324
325std::future<void>
326ClangdServer::scheduleCancelRebuild(std::shared_ptr<CppFile> Resources) {
327 std::promise<void> DonePromise;
328 std::future<void> DoneFuture = DonePromise.get_future();
329 if (!Resources) {
330 // No need to schedule any cleanup.
331 DonePromise.set_value();
332 return DoneFuture;
333 }
334
335 std::future<void> DeferredCancel = Resources->deferCancelRebuild();
336 auto CancelReparses = [Resources](std::promise<void> DonePromise,
337 std::future<void> DeferredCancel) {
338 FulfillPromiseGuard Guard(DonePromise);
339 DeferredCancel.get();
340 };
341 WorkScheduler.addToFront(std::move(CancelReparses), std::move(DonePromise),
342 std::move(DeferredCancel));
343 return DoneFuture;
344}