blob: 0af9e6fe003103b6faa5416650e1da72148d4413 [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/CompilerInstance.h"
13#include "clang/Frontend/CompilerInvocation.h"
14#include "clang/Tooling/CompilationDatabase.h"
Ilya Biryukovafb55542017-05-16 14:40:30 +000015#include "llvm/ADT/ArrayRef.h"
Ilya Biryukov38d79772017-05-16 09:38:59 +000016#include "llvm/Support/FileSystem.h"
Marc-Andre Laperle37de9712017-09-27 15:31:17 +000017#include "llvm/Support/Path.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) {
Ilya Biryukov08e6ccb2017-10-09 16:26:26 +0000102 UniqueFunction<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 Biryukov08e6ccb2017-10-09 16:26:26 +0000123 Request();
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000124 }
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 Biryukovf4e95d72017-09-20 19:32:06 +0000154 SnippetCompletions(SnippetCompletions), WorkScheduler(AsyncThreadsCount) {
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000155}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000156
Marc-Andre Laperle37de9712017-09-27 15:31:17 +0000157void ClangdServer::setRootPath(PathRef RootPath) {
158 std::string NewRootPath = llvm::sys::path::convert_to_slash(
159 RootPath, llvm::sys::path::Style::posix);
160 if (llvm::sys::fs::is_directory(NewRootPath))
161 this->RootPath = NewRootPath;
162}
163
Ilya Biryukov02d58702017-08-01 15:51:38 +0000164std::future<void> ClangdServer::addDocument(PathRef File, StringRef Contents) {
Ilya Biryukovf01af682017-05-23 13:42:59 +0000165 DocVersion Version = DraftMgr.updateDraft(File, Contents);
Ilya Biryukovf01af682017-05-23 13:42:59 +0000166
Ilya Biryukov02d58702017-08-01 15:51:38 +0000167 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
Marc-Andre Laperle37de9712017-09-27 15:31:17 +0000168 std::shared_ptr<CppFile> Resources = Units.getOrCreateFile(
169 File, ResourceDir, CDB, PCHs, TaggedFS.Value, Logger);
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000170 return scheduleReparseAndDiags(File, VersionedDraft{Version, Contents.str()},
171 std::move(Resources), std::move(TaggedFS));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000172}
173
Ilya Biryukov02d58702017-08-01 15:51:38 +0000174std::future<void> ClangdServer::removeDocument(PathRef File) {
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000175 DraftMgr.removeDraft(File);
176 std::shared_ptr<CppFile> Resources = Units.removeIfPresent(File);
177 return scheduleCancelRebuild(std::move(Resources));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000178}
179
Ilya Biryukov02d58702017-08-01 15:51:38 +0000180std::future<void> ClangdServer::forceReparse(PathRef File) {
Ilya Biryukov91dbf5b2017-08-14 08:37:32 +0000181 auto FileContents = DraftMgr.getDraft(File);
182 assert(FileContents.Draft &&
183 "forceReparse() was called for non-added document");
184
185 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
186 auto Recreated = Units.recreateFileIfCompileCommandChanged(
Ilya Biryukove5128f72017-09-20 07:24:15 +0000187 File, ResourceDir, CDB, PCHs, TaggedFS.Value, Logger);
Ilya Biryukov91dbf5b2017-08-14 08:37:32 +0000188
189 // Note that std::future from this cleanup action is ignored.
190 scheduleCancelRebuild(std::move(Recreated.RemovedFile));
191 // Schedule a reparse.
192 return scheduleReparseAndDiags(File, std::move(FileContents),
193 std::move(Recreated.FileInCollection),
194 std::move(TaggedFS));
Ilya Biryukov0f62ed22017-05-26 12:26:51 +0000195}
196
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000197std::future<Tagged<std::vector<CompletionItem>>>
Ilya Biryukov0e27ce42017-06-13 14:15:56 +0000198ClangdServer::codeComplete(PathRef File, Position Pos,
Ilya Biryukoved99e4c2017-07-31 17:09:29 +0000199 llvm::Optional<StringRef> OverridenContents,
200 IntrusiveRefCntPtr<vfs::FileSystem> *UsedFS) {
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000201 std::string Contents;
202 if (OverridenContents) {
203 Contents = *OverridenContents;
204 } else {
Ilya Biryukov0e27ce42017-06-13 14:15:56 +0000205 auto FileContents = DraftMgr.getDraft(File);
206 assert(FileContents.Draft &&
207 "codeComplete is called for non-added document");
208
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000209 Contents = std::move(*FileContents.Draft);
Ilya Biryukov0e27ce42017-06-13 14:15:56 +0000210 }
Ilya Biryukov38d79772017-05-16 09:38:59 +0000211
Ilya Biryukovaf0c04b2017-06-14 09:46:44 +0000212 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
Ilya Biryukoved99e4c2017-07-31 17:09:29 +0000213 if (UsedFS)
214 *UsedFS = TaggedFS.Value;
215
Ilya Biryukov02d58702017-08-01 15:51:38 +0000216 std::shared_ptr<CppFile> Resources = Units.getFile(File);
217 assert(Resources && "Calling completion on non-added file");
218
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000219 using PackagedTask =
220 std::packaged_task<Tagged<std::vector<CompletionItem>>()>;
221
222 // Remember the current Preamble and use it when async task starts executing.
223 // At the point when async task starts executing, we may have a different
224 // Preamble in Resources. However, we assume the Preamble that we obtain here
225 // is reusable in completion more often.
226 std::shared_ptr<const PreambleData> Preamble =
227 Resources->getPossiblyStalePreamble();
228 // A task that will be run asynchronously.
229 PackagedTask Task([=]() mutable { // 'mutable' to reassign Preamble variable.
230 if (!Preamble) {
231 // Maybe we built some preamble before processing this request.
232 Preamble = Resources->getPossiblyStalePreamble();
233 }
234 // FIXME(ibiryukov): even if Preamble is non-null, we may want to check
235 // both the old and the new version in case only one of them matches.
236
237 std::vector<CompletionItem> Result = clangd::codeComplete(
238 File, Resources->getCompileCommand(),
239 Preamble ? &Preamble->Preamble : nullptr, Contents, Pos, TaggedFS.Value,
240 PCHs, SnippetCompletions, Logger);
241 return make_tagged(std::move(Result), std::move(TaggedFS.Tag));
242 });
243
244 auto Future = Task.get_future();
245 // FIXME(ibiryukov): to reduce overhead for wrapping the same callable
246 // multiple times, ClangdScheduler should return future<> itself.
247 WorkScheduler.addToFront([](PackagedTask Task) { Task(); }, std::move(Task));
248 return Future;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000249}
Ilya Biryukovf01af682017-05-23 13:42:59 +0000250
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000251Tagged<SignatureHelp>
252ClangdServer::signatureHelp(PathRef File, Position Pos,
253 llvm::Optional<StringRef> OverridenContents,
254 IntrusiveRefCntPtr<vfs::FileSystem> *UsedFS) {
255 std::string DraftStorage;
256 if (!OverridenContents) {
257 auto FileContents = DraftMgr.getDraft(File);
258 assert(FileContents.Draft &&
259 "signatureHelp is called for non-added document");
260
261 DraftStorage = std::move(*FileContents.Draft);
262 OverridenContents = DraftStorage;
263 }
264
265 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
266 if (UsedFS)
267 *UsedFS = TaggedFS.Value;
268
269 std::shared_ptr<CppFile> Resources = Units.getFile(File);
270 assert(Resources && "Calling signatureHelp on non-added file");
271
272 auto Preamble = Resources->getPossiblyStalePreamble();
273 auto Result = clangd::signatureHelp(File, Resources->getCompileCommand(),
274 Preamble ? &Preamble->Preamble : nullptr,
275 *OverridenContents, Pos, TaggedFS.Value,
276 PCHs, Logger);
277 return make_tagged(std::move(Result), TaggedFS.Tag);
278}
279
Ilya Biryukovafb55542017-05-16 14:40:30 +0000280std::vector<tooling::Replacement> ClangdServer::formatRange(PathRef File,
281 Range Rng) {
282 std::string Code = getDocument(File);
283
284 size_t Begin = positionToOffset(Code, Rng.start);
285 size_t Len = positionToOffset(Code, Rng.end) - Begin;
286 return formatCode(Code, File, {tooling::Range(Begin, Len)});
287}
288
289std::vector<tooling::Replacement> ClangdServer::formatFile(PathRef File) {
290 // Format everything.
291 std::string Code = getDocument(File);
292 return formatCode(Code, File, {tooling::Range(0, Code.size())});
293}
294
295std::vector<tooling::Replacement> ClangdServer::formatOnType(PathRef File,
296 Position Pos) {
297 // Look for the previous opening brace from the character position and
298 // format starting from there.
299 std::string Code = getDocument(File);
300 size_t CursorPos = positionToOffset(Code, Pos);
301 size_t PreviousLBracePos = StringRef(Code).find_last_of('{', CursorPos);
302 if (PreviousLBracePos == StringRef::npos)
303 PreviousLBracePos = CursorPos;
304 size_t Len = 1 + CursorPos - PreviousLBracePos;
305
306 return formatCode(Code, File, {tooling::Range(PreviousLBracePos, Len)});
307}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000308
309std::string ClangdServer::getDocument(PathRef File) {
310 auto draft = DraftMgr.getDraft(File);
311 assert(draft.Draft && "File is not tracked, cannot get contents");
312 return *draft.Draft;
313}
314
Ilya Biryukovf01af682017-05-23 13:42:59 +0000315std::string ClangdServer::dumpAST(PathRef File) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000316 std::shared_ptr<CppFile> Resources = Units.getFile(File);
317 assert(Resources && "dumpAST is called for non-added document");
Ilya Biryukov38d79772017-05-16 09:38:59 +0000318
Ilya Biryukov02d58702017-08-01 15:51:38 +0000319 std::string Result;
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +0000320 Resources->getAST().get()->runUnderLock([&Result](ParsedAST *AST) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000321 llvm::raw_string_ostream ResultOS(Result);
322 if (AST) {
323 clangd::dumpAST(*AST, ResultOS);
324 } else {
325 ResultOS << "<no-ast>";
326 }
327 ResultOS.flush();
Ilya Biryukovf01af682017-05-23 13:42:59 +0000328 });
Ilya Biryukov02d58702017-08-01 15:51:38 +0000329 return Result;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000330}
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000331
Ilya Biryukov02d58702017-08-01 15:51:38 +0000332Tagged<std::vector<Location>> ClangdServer::findDefinitions(PathRef File,
333 Position Pos) {
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000334 auto FileContents = DraftMgr.getDraft(File);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000335 assert(FileContents.Draft &&
336 "findDefinitions is called for non-added document");
337
338 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
339
340 std::shared_ptr<CppFile> Resources = Units.getFile(File);
341 assert(Resources && "Calling findDefinitions on non-added file");
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000342
343 std::vector<Location> Result;
Ilya Biryukove5128f72017-09-20 07:24:15 +0000344 Resources->getAST().get()->runUnderLock([Pos, &Result, this](ParsedAST *AST) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000345 if (!AST)
346 return;
Ilya Biryukove5128f72017-09-20 07:24:15 +0000347 Result = clangd::findDefinitions(*AST, Pos, Logger);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000348 });
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000349 return make_tagged(std::move(Result), TaggedFS.Tag);
350}
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000351
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000352llvm::Optional<Path> ClangdServer::switchSourceHeader(PathRef Path) {
353
354 StringRef SourceExtensions[] = {".cpp", ".c", ".cc", ".cxx",
355 ".c++", ".m", ".mm"};
356 StringRef HeaderExtensions[] = {".h", ".hh", ".hpp", ".hxx", ".inc"};
357
358 StringRef PathExt = llvm::sys::path::extension(Path);
359
360 // Lookup in a list of known extensions.
361 auto SourceIter =
362 std::find_if(std::begin(SourceExtensions), std::end(SourceExtensions),
363 [&PathExt](PathRef SourceExt) {
364 return SourceExt.equals_lower(PathExt);
365 });
366 bool IsSource = SourceIter != std::end(SourceExtensions);
367
368 auto HeaderIter =
369 std::find_if(std::begin(HeaderExtensions), std::end(HeaderExtensions),
370 [&PathExt](PathRef HeaderExt) {
371 return HeaderExt.equals_lower(PathExt);
372 });
373
374 bool IsHeader = HeaderIter != std::end(HeaderExtensions);
375
376 // We can only switch between extensions known extensions.
377 if (!IsSource && !IsHeader)
378 return llvm::None;
379
380 // Array to lookup extensions for the switch. An opposite of where original
381 // extension was found.
382 ArrayRef<StringRef> NewExts;
383 if (IsSource)
384 NewExts = HeaderExtensions;
385 else
386 NewExts = SourceExtensions;
387
388 // Storage for the new path.
389 SmallString<128> NewPath = StringRef(Path);
390
391 // Instance of vfs::FileSystem, used for file existence checks.
392 auto FS = FSProvider.getTaggedFileSystem(Path).Value;
393
394 // Loop through switched extension candidates.
395 for (StringRef NewExt : NewExts) {
396 llvm::sys::path::replace_extension(NewPath, NewExt);
397 if (FS->exists(NewPath))
398 return NewPath.str().str(); // First str() to convert from SmallString to
399 // StringRef, second to convert from StringRef
400 // to std::string
Ilya Biryukov33334942017-10-06 14:39:39 +0000401
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000402 // Also check NewExt in upper-case, just in case.
403 llvm::sys::path::replace_extension(NewPath, NewExt.upper());
404 if (FS->exists(NewPath))
405 return NewPath.str().str();
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000406 }
407
408 return llvm::None;
409}
410
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000411std::future<void> ClangdServer::scheduleReparseAndDiags(
412 PathRef File, VersionedDraft Contents, std::shared_ptr<CppFile> Resources,
413 Tagged<IntrusiveRefCntPtr<vfs::FileSystem>> TaggedFS) {
414
415 assert(Contents.Draft && "Draft must have contents");
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000416 UniqueFunction<llvm::Optional<std::vector<DiagWithFixIts>>()>
417 DeferredRebuild =
418 Resources->deferRebuild(*Contents.Draft, TaggedFS.Value);
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000419 std::promise<void> DonePromise;
420 std::future<void> DoneFuture = DonePromise.get_future();
421
422 DocVersion Version = Contents.Version;
423 Path FileStr = File;
424 VFSTag Tag = TaggedFS.Tag;
425 auto ReparseAndPublishDiags =
426 [this, FileStr, Version,
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000427 Tag](UniqueFunction<llvm::Optional<std::vector<DiagWithFixIts>>()>
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000428 DeferredRebuild,
429 std::promise<void> DonePromise) -> void {
430 FulfillPromiseGuard Guard(DonePromise);
431
432 auto CurrentVersion = DraftMgr.getVersion(FileStr);
433 if (CurrentVersion != Version)
434 return; // This request is outdated
435
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000436 auto Diags = DeferredRebuild();
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000437 if (!Diags)
438 return; // A new reparse was requested before this one completed.
Ilya Biryukov47f22022017-09-20 12:58:55 +0000439
440 // We need to serialize access to resulting diagnostics to avoid calling
441 // `onDiagnosticsReady` in the wrong order.
442 std::lock_guard<std::mutex> DiagsLock(DiagnosticsMutex);
443 DocVersion &LastReportedDiagsVersion = ReportedDiagnosticVersions[FileStr];
444 // FIXME(ibiryukov): get rid of '<' comparison here. In the current
445 // implementation diagnostics will not be reported after version counters'
446 // overflow. This should not happen in practice, since DocVersion is a
447 // 64-bit unsigned integer.
448 if (Version < LastReportedDiagsVersion)
449 return;
450 LastReportedDiagsVersion = Version;
451
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000452 DiagConsumer.onDiagnosticsReady(FileStr,
453 make_tagged(std::move(*Diags), Tag));
454 };
455
456 WorkScheduler.addToFront(std::move(ReparseAndPublishDiags),
457 std::move(DeferredRebuild), std::move(DonePromise));
458 return DoneFuture;
459}
460
461std::future<void>
462ClangdServer::scheduleCancelRebuild(std::shared_ptr<CppFile> Resources) {
463 std::promise<void> DonePromise;
464 std::future<void> DoneFuture = DonePromise.get_future();
465 if (!Resources) {
466 // No need to schedule any cleanup.
467 DonePromise.set_value();
468 return DoneFuture;
469 }
470
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000471 UniqueFunction<void()> DeferredCancel = Resources->deferCancelRebuild();
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000472 auto CancelReparses = [Resources](std::promise<void> DonePromise,
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000473 UniqueFunction<void()> DeferredCancel) {
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000474 FulfillPromiseGuard Guard(DonePromise);
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000475 DeferredCancel();
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000476 };
477 WorkScheduler.addToFront(std::move(CancelReparses), std::move(DonePromise),
478 std::move(DeferredCancel));
479 return DoneFuture;
480}
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000481
482void ClangdServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
483 // FIXME: Do nothing for now. This will be used for indexing and potentially
484 // invalidating other caches.
485}