blob: 9338cb1b213e9bd0fec3b94355c398a0248c4c92 [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 Biryukovb080cb12017-10-23 14:46:48 +0000147 unsigned AsyncThreadsCount,
148 clangd::CodeCompleteOptions CodeCompleteOpts,
Ilya Biryukove5128f72017-09-20 07:24:15 +0000149 clangd::Logger &Logger,
Ilya Biryukova46f7a92017-06-28 10:34:50 +0000150 llvm::Optional<StringRef> ResourceDir)
Ilya Biryukove5128f72017-09-20 07:24:15 +0000151 : Logger(Logger), CDB(CDB), DiagConsumer(DiagConsumer),
152 FSProvider(FSProvider),
Ilya Biryukova46f7a92017-06-28 10:34:50 +0000153 ResourceDir(ResourceDir ? ResourceDir->str() : getStandardResourceDir()),
Ilya Biryukov38d79772017-05-16 09:38:59 +0000154 PCHs(std::make_shared<PCHContainerOperations>()),
Ilya Biryukovb080cb12017-10-23 14:46:48 +0000155 CodeCompleteOpts(CodeCompleteOpts), WorkScheduler(AsyncThreadsCount) {}
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 Biryukov90bbcfd2017-10-25 09:35:10 +0000201 using ResultType = Tagged<std::vector<CompletionItem>>;
202
203 std::promise<ResultType> ResultPromise;
204
205 auto Callback = [](std::promise<ResultType> ResultPromise,
206 ResultType Result) -> void {
207 ResultPromise.set_value(std::move(Result));
208 };
209
210 std::future<ResultType> ResultFuture = ResultPromise.get_future();
211 codeComplete(BindWithForward(Callback, std::move(ResultPromise)), File, Pos,
212 OverridenContents, UsedFS);
213 return ResultFuture;
214}
215
216void ClangdServer::codeComplete(
217 UniqueFunction<void(Tagged<std::vector<CompletionItem>>)> Callback,
218 PathRef File, Position Pos, llvm::Optional<StringRef> OverridenContents,
219 IntrusiveRefCntPtr<vfs::FileSystem> *UsedFS) {
220 using CallbackType =
221 UniqueFunction<void(Tagged<std::vector<CompletionItem>>)>;
222
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000223 std::string Contents;
224 if (OverridenContents) {
225 Contents = *OverridenContents;
226 } else {
Ilya Biryukov0e27ce42017-06-13 14:15:56 +0000227 auto FileContents = DraftMgr.getDraft(File);
228 assert(FileContents.Draft &&
229 "codeComplete is called for non-added document");
230
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000231 Contents = std::move(*FileContents.Draft);
Ilya Biryukov0e27ce42017-06-13 14:15:56 +0000232 }
Ilya Biryukov38d79772017-05-16 09:38:59 +0000233
Ilya Biryukovaf0c04b2017-06-14 09:46:44 +0000234 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
Ilya Biryukoved99e4c2017-07-31 17:09:29 +0000235 if (UsedFS)
236 *UsedFS = TaggedFS.Value;
237
Ilya Biryukov02d58702017-08-01 15:51:38 +0000238 std::shared_ptr<CppFile> Resources = Units.getFile(File);
239 assert(Resources && "Calling completion on non-added file");
240
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000241 // Remember the current Preamble and use it when async task starts executing.
242 // At the point when async task starts executing, we may have a different
243 // Preamble in Resources. However, we assume the Preamble that we obtain here
244 // is reusable in completion more often.
245 std::shared_ptr<const PreambleData> Preamble =
246 Resources->getPossiblyStalePreamble();
247 // A task that will be run asynchronously.
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000248 auto Task =
249 // 'mutable' to reassign Preamble variable.
250 [=](CallbackType Callback) mutable {
251 if (!Preamble) {
252 // Maybe we built some preamble before processing this request.
253 Preamble = Resources->getPossiblyStalePreamble();
254 }
255 // FIXME(ibiryukov): even if Preamble is non-null, we may want to check
256 // both the old and the new version in case only one of them matches.
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000257
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000258 std::vector<CompletionItem> Result = clangd::codeComplete(
259 File, Resources->getCompileCommand(),
260 Preamble ? &Preamble->Preamble : nullptr, Contents, Pos,
261 TaggedFS.Value, PCHs, CodeCompleteOpts, Logger);
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000262
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000263 Callback(make_tagged(std::move(Result), std::move(TaggedFS.Tag)));
264 };
265
266 WorkScheduler.addToFront(std::move(Task), std::move(Callback));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000267}
Ilya Biryukovf01af682017-05-23 13:42:59 +0000268
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000269Tagged<SignatureHelp>
270ClangdServer::signatureHelp(PathRef File, Position Pos,
271 llvm::Optional<StringRef> OverridenContents,
272 IntrusiveRefCntPtr<vfs::FileSystem> *UsedFS) {
273 std::string DraftStorage;
274 if (!OverridenContents) {
275 auto FileContents = DraftMgr.getDraft(File);
276 assert(FileContents.Draft &&
277 "signatureHelp is called for non-added document");
278
279 DraftStorage = std::move(*FileContents.Draft);
280 OverridenContents = DraftStorage;
281 }
282
283 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
284 if (UsedFS)
285 *UsedFS = TaggedFS.Value;
286
287 std::shared_ptr<CppFile> Resources = Units.getFile(File);
288 assert(Resources && "Calling signatureHelp on non-added file");
289
290 auto Preamble = Resources->getPossiblyStalePreamble();
291 auto Result = clangd::signatureHelp(File, Resources->getCompileCommand(),
292 Preamble ? &Preamble->Preamble : nullptr,
293 *OverridenContents, Pos, TaggedFS.Value,
294 PCHs, Logger);
295 return make_tagged(std::move(Result), TaggedFS.Tag);
296}
297
Ilya Biryukovafb55542017-05-16 14:40:30 +0000298std::vector<tooling::Replacement> ClangdServer::formatRange(PathRef File,
299 Range Rng) {
300 std::string Code = getDocument(File);
301
302 size_t Begin = positionToOffset(Code, Rng.start);
303 size_t Len = positionToOffset(Code, Rng.end) - Begin;
304 return formatCode(Code, File, {tooling::Range(Begin, Len)});
305}
306
307std::vector<tooling::Replacement> ClangdServer::formatFile(PathRef File) {
308 // Format everything.
309 std::string Code = getDocument(File);
310 return formatCode(Code, File, {tooling::Range(0, Code.size())});
311}
312
313std::vector<tooling::Replacement> ClangdServer::formatOnType(PathRef File,
314 Position Pos) {
315 // Look for the previous opening brace from the character position and
316 // format starting from there.
317 std::string Code = getDocument(File);
318 size_t CursorPos = positionToOffset(Code, Pos);
319 size_t PreviousLBracePos = StringRef(Code).find_last_of('{', CursorPos);
320 if (PreviousLBracePos == StringRef::npos)
321 PreviousLBracePos = CursorPos;
322 size_t Len = 1 + CursorPos - PreviousLBracePos;
323
324 return formatCode(Code, File, {tooling::Range(PreviousLBracePos, Len)});
325}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000326
327std::string ClangdServer::getDocument(PathRef File) {
328 auto draft = DraftMgr.getDraft(File);
329 assert(draft.Draft && "File is not tracked, cannot get contents");
330 return *draft.Draft;
331}
332
Ilya Biryukovf01af682017-05-23 13:42:59 +0000333std::string ClangdServer::dumpAST(PathRef File) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000334 std::shared_ptr<CppFile> Resources = Units.getFile(File);
335 assert(Resources && "dumpAST is called for non-added document");
Ilya Biryukov38d79772017-05-16 09:38:59 +0000336
Ilya Biryukov02d58702017-08-01 15:51:38 +0000337 std::string Result;
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +0000338 Resources->getAST().get()->runUnderLock([&Result](ParsedAST *AST) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000339 llvm::raw_string_ostream ResultOS(Result);
340 if (AST) {
341 clangd::dumpAST(*AST, ResultOS);
342 } else {
343 ResultOS << "<no-ast>";
344 }
345 ResultOS.flush();
Ilya Biryukovf01af682017-05-23 13:42:59 +0000346 });
Ilya Biryukov02d58702017-08-01 15:51:38 +0000347 return Result;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000348}
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000349
Ilya Biryukov02d58702017-08-01 15:51:38 +0000350Tagged<std::vector<Location>> ClangdServer::findDefinitions(PathRef File,
351 Position Pos) {
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000352 auto FileContents = DraftMgr.getDraft(File);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000353 assert(FileContents.Draft &&
354 "findDefinitions is called for non-added document");
355
356 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
357
358 std::shared_ptr<CppFile> Resources = Units.getFile(File);
359 assert(Resources && "Calling findDefinitions on non-added file");
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000360
361 std::vector<Location> Result;
Ilya Biryukove5128f72017-09-20 07:24:15 +0000362 Resources->getAST().get()->runUnderLock([Pos, &Result, this](ParsedAST *AST) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000363 if (!AST)
364 return;
Ilya Biryukove5128f72017-09-20 07:24:15 +0000365 Result = clangd::findDefinitions(*AST, Pos, Logger);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000366 });
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000367 return make_tagged(std::move(Result), TaggedFS.Tag);
368}
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000369
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000370llvm::Optional<Path> ClangdServer::switchSourceHeader(PathRef Path) {
371
372 StringRef SourceExtensions[] = {".cpp", ".c", ".cc", ".cxx",
373 ".c++", ".m", ".mm"};
374 StringRef HeaderExtensions[] = {".h", ".hh", ".hpp", ".hxx", ".inc"};
375
376 StringRef PathExt = llvm::sys::path::extension(Path);
377
378 // Lookup in a list of known extensions.
379 auto SourceIter =
380 std::find_if(std::begin(SourceExtensions), std::end(SourceExtensions),
381 [&PathExt](PathRef SourceExt) {
382 return SourceExt.equals_lower(PathExt);
383 });
384 bool IsSource = SourceIter != std::end(SourceExtensions);
385
386 auto HeaderIter =
387 std::find_if(std::begin(HeaderExtensions), std::end(HeaderExtensions),
388 [&PathExt](PathRef HeaderExt) {
389 return HeaderExt.equals_lower(PathExt);
390 });
391
392 bool IsHeader = HeaderIter != std::end(HeaderExtensions);
393
394 // We can only switch between extensions known extensions.
395 if (!IsSource && !IsHeader)
396 return llvm::None;
397
398 // Array to lookup extensions for the switch. An opposite of where original
399 // extension was found.
400 ArrayRef<StringRef> NewExts;
401 if (IsSource)
402 NewExts = HeaderExtensions;
403 else
404 NewExts = SourceExtensions;
405
406 // Storage for the new path.
407 SmallString<128> NewPath = StringRef(Path);
408
409 // Instance of vfs::FileSystem, used for file existence checks.
410 auto FS = FSProvider.getTaggedFileSystem(Path).Value;
411
412 // Loop through switched extension candidates.
413 for (StringRef NewExt : NewExts) {
414 llvm::sys::path::replace_extension(NewPath, NewExt);
415 if (FS->exists(NewPath))
416 return NewPath.str().str(); // First str() to convert from SmallString to
417 // StringRef, second to convert from StringRef
418 // to std::string
Ilya Biryukov33334942017-10-06 14:39:39 +0000419
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000420 // Also check NewExt in upper-case, just in case.
421 llvm::sys::path::replace_extension(NewPath, NewExt.upper());
422 if (FS->exists(NewPath))
423 return NewPath.str().str();
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000424 }
425
426 return llvm::None;
427}
428
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000429std::future<void> ClangdServer::scheduleReparseAndDiags(
430 PathRef File, VersionedDraft Contents, std::shared_ptr<CppFile> Resources,
431 Tagged<IntrusiveRefCntPtr<vfs::FileSystem>> TaggedFS) {
432
433 assert(Contents.Draft && "Draft must have contents");
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000434 UniqueFunction<llvm::Optional<std::vector<DiagWithFixIts>>()>
435 DeferredRebuild =
436 Resources->deferRebuild(*Contents.Draft, TaggedFS.Value);
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000437 std::promise<void> DonePromise;
438 std::future<void> DoneFuture = DonePromise.get_future();
439
440 DocVersion Version = Contents.Version;
441 Path FileStr = File;
442 VFSTag Tag = TaggedFS.Tag;
443 auto ReparseAndPublishDiags =
444 [this, FileStr, Version,
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000445 Tag](UniqueFunction<llvm::Optional<std::vector<DiagWithFixIts>>()>
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000446 DeferredRebuild,
447 std::promise<void> DonePromise) -> void {
448 FulfillPromiseGuard Guard(DonePromise);
449
450 auto CurrentVersion = DraftMgr.getVersion(FileStr);
451 if (CurrentVersion != Version)
452 return; // This request is outdated
453
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000454 auto Diags = DeferredRebuild();
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000455 if (!Diags)
456 return; // A new reparse was requested before this one completed.
Ilya Biryukov47f22022017-09-20 12:58:55 +0000457
458 // We need to serialize access to resulting diagnostics to avoid calling
459 // `onDiagnosticsReady` in the wrong order.
460 std::lock_guard<std::mutex> DiagsLock(DiagnosticsMutex);
461 DocVersion &LastReportedDiagsVersion = ReportedDiagnosticVersions[FileStr];
462 // FIXME(ibiryukov): get rid of '<' comparison here. In the current
463 // implementation diagnostics will not be reported after version counters'
464 // overflow. This should not happen in practice, since DocVersion is a
465 // 64-bit unsigned integer.
466 if (Version < LastReportedDiagsVersion)
467 return;
468 LastReportedDiagsVersion = Version;
469
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000470 DiagConsumer.onDiagnosticsReady(FileStr,
471 make_tagged(std::move(*Diags), Tag));
472 };
473
474 WorkScheduler.addToFront(std::move(ReparseAndPublishDiags),
475 std::move(DeferredRebuild), std::move(DonePromise));
476 return DoneFuture;
477}
478
479std::future<void>
480ClangdServer::scheduleCancelRebuild(std::shared_ptr<CppFile> Resources) {
481 std::promise<void> DonePromise;
482 std::future<void> DoneFuture = DonePromise.get_future();
483 if (!Resources) {
484 // No need to schedule any cleanup.
485 DonePromise.set_value();
486 return DoneFuture;
487 }
488
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000489 UniqueFunction<void()> DeferredCancel = Resources->deferCancelRebuild();
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000490 auto CancelReparses = [Resources](std::promise<void> DonePromise,
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000491 UniqueFunction<void()> DeferredCancel) {
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000492 FulfillPromiseGuard Guard(DonePromise);
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000493 DeferredCancel();
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000494 };
495 WorkScheduler.addToFront(std::move(CancelReparses), std::move(DonePromise),
496 std::move(DeferredCancel));
497 return DoneFuture;
498}
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000499
500void ClangdServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
501 // FIXME: Do nothing for now. This will be used for indexing and potentially
502 // invalidating other caches.
503}