blob: 528b6eba3f24cda44b0a381eb7092d59bf65f54b [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"
Benjamin Krameree19f162017-10-26 12:28:13 +000016#include "llvm/Support/Errc.h"
Ilya Biryukov38d79772017-05-16 09:38:59 +000017#include "llvm/Support/FileSystem.h"
Marc-Andre Laperle37de9712017-09-27 15:31:17 +000018#include "llvm/Support/Path.h"
Ilya Biryukovf01af682017-05-23 13:42:59 +000019#include "llvm/Support/raw_ostream.h"
20#include <future>
Ilya Biryukov38d79772017-05-16 09:38:59 +000021
Ilya Biryukov2f314102017-05-16 10:06:20 +000022using namespace clang;
Ilya Biryukov38d79772017-05-16 09:38:59 +000023using namespace clang::clangd;
24
Ilya Biryukovafb55542017-05-16 14:40:30 +000025namespace {
26
Ilya Biryukov02d58702017-08-01 15:51:38 +000027class FulfillPromiseGuard {
28public:
29 FulfillPromiseGuard(std::promise<void> &Promise) : Promise(Promise) {}
30
31 ~FulfillPromiseGuard() { Promise.set_value(); }
32
33private:
34 std::promise<void> &Promise;
35};
36
Ilya Biryukovafb55542017-05-16 14:40:30 +000037std::vector<tooling::Replacement> formatCode(StringRef Code, StringRef Filename,
38 ArrayRef<tooling::Range> Ranges) {
39 // Call clang-format.
40 // FIXME: Don't ignore style.
41 format::FormatStyle Style = format::getLLVMStyle();
42 auto Result = format::reformat(Style, Code, Ranges, Filename);
43
44 return std::vector<tooling::Replacement>(Result.begin(), Result.end());
45}
46
Ilya Biryukova46f7a92017-06-28 10:34:50 +000047std::string getStandardResourceDir() {
48 static int Dummy; // Just an address in this process.
49 return CompilerInvocation::GetResourcesPath("clangd", (void *)&Dummy);
50}
51
Ilya Biryukovafb55542017-05-16 14:40:30 +000052} // namespace
53
54size_t clangd::positionToOffset(StringRef Code, Position P) {
55 size_t Offset = 0;
56 for (int I = 0; I != P.line; ++I) {
57 // FIXME: \r\n
58 // FIXME: UTF-8
59 size_t F = Code.find('\n', Offset);
60 if (F == StringRef::npos)
61 return 0; // FIXME: Is this reasonable?
62 Offset = F + 1;
63 }
64 return (Offset == 0 ? 0 : (Offset - 1)) + P.character;
65}
66
67/// Turn an offset in Code into a [line, column] pair.
68Position clangd::offsetToPosition(StringRef Code, size_t Offset) {
69 StringRef JustBefore = Code.substr(0, Offset);
70 // FIXME: \r\n
71 // FIXME: UTF-8
72 int Lines = JustBefore.count('\n');
73 int Cols = JustBefore.size() - JustBefore.rfind('\n') - 1;
74 return {Lines, Cols};
75}
76
Ilya Biryukov22602992017-05-30 15:11:02 +000077Tagged<IntrusiveRefCntPtr<vfs::FileSystem>>
Ilya Biryukovaf0c04b2017-06-14 09:46:44 +000078RealFileSystemProvider::getTaggedFileSystem(PathRef File) {
Ilya Biryukov22602992017-05-30 15:11:02 +000079 return make_tagged(vfs::getRealFileSystem(), VFSTag());
Ilya Biryukov0f62ed22017-05-26 12:26:51 +000080}
81
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +000082unsigned clangd::getDefaultAsyncThreadsCount() {
83 unsigned HardwareConcurrency = std::thread::hardware_concurrency();
84 // C++ standard says that hardware_concurrency()
85 // may return 0, fallback to 1 worker thread in
86 // that case.
87 if (HardwareConcurrency == 0)
88 return 1;
89 return HardwareConcurrency;
90}
91
92ClangdScheduler::ClangdScheduler(unsigned AsyncThreadsCount)
93 : RunSynchronously(AsyncThreadsCount == 0) {
Ilya Biryukov38d79772017-05-16 09:38:59 +000094 if (RunSynchronously) {
95 // Don't start the worker thread if we're running synchronously
96 return;
97 }
98
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +000099 Workers.reserve(AsyncThreadsCount);
100 for (unsigned I = 0; I < AsyncThreadsCount; ++I) {
101 Workers.push_back(std::thread([this]() {
102 while (true) {
Ilya Biryukov08e6ccb2017-10-09 16:26:26 +0000103 UniqueFunction<void()> Request;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000104
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000105 // Pick request from the queue
106 {
107 std::unique_lock<std::mutex> Lock(Mutex);
108 // Wait for more requests.
109 RequestCV.wait(Lock,
110 [this] { return !RequestQueue.empty() || Done; });
111 if (Done)
112 return;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000113
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000114 assert(!RequestQueue.empty() && "RequestQueue was empty");
Ilya Biryukov38d79772017-05-16 09:38:59 +0000115
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000116 // We process requests starting from the front of the queue. Users of
117 // ClangdScheduler have a way to prioritise their requests by putting
118 // them to the either side of the queue (using either addToEnd or
119 // addToFront).
120 Request = std::move(RequestQueue.front());
121 RequestQueue.pop_front();
122 } // unlock Mutex
Ilya Biryukov38d79772017-05-16 09:38:59 +0000123
Ilya Biryukov08e6ccb2017-10-09 16:26:26 +0000124 Request();
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000125 }
126 }));
127 }
Ilya Biryukov38d79772017-05-16 09:38:59 +0000128}
129
130ClangdScheduler::~ClangdScheduler() {
131 if (RunSynchronously)
132 return; // no worker thread is running in that case
133
134 {
135 std::lock_guard<std::mutex> Lock(Mutex);
136 // Wake up the worker thread
137 Done = true;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000138 } // unlock Mutex
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000139 RequestCV.notify_all();
140
141 for (auto &Worker : Workers)
142 Worker.join();
Ilya Biryukov38d79772017-05-16 09:38:59 +0000143}
144
Ilya Biryukov103c9512017-06-13 15:59:43 +0000145ClangdServer::ClangdServer(GlobalCompilationDatabase &CDB,
146 DiagnosticsConsumer &DiagConsumer,
147 FileSystemProvider &FSProvider,
Ilya Biryukovb080cb12017-10-23 14:46:48 +0000148 unsigned AsyncThreadsCount,
149 clangd::CodeCompleteOptions CodeCompleteOpts,
Ilya Biryukove5128f72017-09-20 07:24:15 +0000150 clangd::Logger &Logger,
Ilya Biryukova46f7a92017-06-28 10:34:50 +0000151 llvm::Optional<StringRef> ResourceDir)
Ilya Biryukove5128f72017-09-20 07:24:15 +0000152 : Logger(Logger), CDB(CDB), DiagConsumer(DiagConsumer),
153 FSProvider(FSProvider),
Ilya Biryukova46f7a92017-06-28 10:34:50 +0000154 ResourceDir(ResourceDir ? ResourceDir->str() : getStandardResourceDir()),
Ilya Biryukov38d79772017-05-16 09:38:59 +0000155 PCHs(std::make_shared<PCHContainerOperations>()),
Ilya Biryukovb080cb12017-10-23 14:46:48 +0000156 CodeCompleteOpts(CodeCompleteOpts), WorkScheduler(AsyncThreadsCount) {}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000157
Marc-Andre Laperle37de9712017-09-27 15:31:17 +0000158void ClangdServer::setRootPath(PathRef RootPath) {
159 std::string NewRootPath = llvm::sys::path::convert_to_slash(
160 RootPath, llvm::sys::path::Style::posix);
161 if (llvm::sys::fs::is_directory(NewRootPath))
162 this->RootPath = NewRootPath;
163}
164
Ilya Biryukov02d58702017-08-01 15:51:38 +0000165std::future<void> ClangdServer::addDocument(PathRef File, StringRef Contents) {
Ilya Biryukovf01af682017-05-23 13:42:59 +0000166 DocVersion Version = DraftMgr.updateDraft(File, Contents);
Ilya Biryukovf01af682017-05-23 13:42:59 +0000167
Ilya Biryukov02d58702017-08-01 15:51:38 +0000168 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
Marc-Andre Laperle37de9712017-09-27 15:31:17 +0000169 std::shared_ptr<CppFile> Resources = Units.getOrCreateFile(
170 File, ResourceDir, CDB, PCHs, TaggedFS.Value, Logger);
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000171 return scheduleReparseAndDiags(File, VersionedDraft{Version, Contents.str()},
172 std::move(Resources), std::move(TaggedFS));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000173}
174
Ilya Biryukov02d58702017-08-01 15:51:38 +0000175std::future<void> ClangdServer::removeDocument(PathRef File) {
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000176 DraftMgr.removeDraft(File);
177 std::shared_ptr<CppFile> Resources = Units.removeIfPresent(File);
178 return scheduleCancelRebuild(std::move(Resources));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000179}
180
Ilya Biryukov02d58702017-08-01 15:51:38 +0000181std::future<void> ClangdServer::forceReparse(PathRef File) {
Ilya Biryukov91dbf5b2017-08-14 08:37:32 +0000182 auto FileContents = DraftMgr.getDraft(File);
183 assert(FileContents.Draft &&
184 "forceReparse() was called for non-added document");
185
186 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
187 auto Recreated = Units.recreateFileIfCompileCommandChanged(
Ilya Biryukove5128f72017-09-20 07:24:15 +0000188 File, ResourceDir, CDB, PCHs, TaggedFS.Value, Logger);
Ilya Biryukov91dbf5b2017-08-14 08:37:32 +0000189
190 // Note that std::future from this cleanup action is ignored.
191 scheduleCancelRebuild(std::move(Recreated.RemovedFile));
192 // Schedule a reparse.
193 return scheduleReparseAndDiags(File, std::move(FileContents),
194 std::move(Recreated.FileInCollection),
195 std::move(TaggedFS));
Ilya Biryukov0f62ed22017-05-26 12:26:51 +0000196}
197
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000198std::future<Tagged<std::vector<CompletionItem>>>
Ilya Biryukov0e27ce42017-06-13 14:15:56 +0000199ClangdServer::codeComplete(PathRef File, Position Pos,
Ilya Biryukoved99e4c2017-07-31 17:09:29 +0000200 llvm::Optional<StringRef> OverridenContents,
201 IntrusiveRefCntPtr<vfs::FileSystem> *UsedFS) {
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000202 using ResultType = Tagged<std::vector<CompletionItem>>;
203
204 std::promise<ResultType> ResultPromise;
205
206 auto Callback = [](std::promise<ResultType> ResultPromise,
207 ResultType Result) -> void {
208 ResultPromise.set_value(std::move(Result));
209 };
210
211 std::future<ResultType> ResultFuture = ResultPromise.get_future();
212 codeComplete(BindWithForward(Callback, std::move(ResultPromise)), File, Pos,
213 OverridenContents, UsedFS);
214 return ResultFuture;
215}
216
217void ClangdServer::codeComplete(
218 UniqueFunction<void(Tagged<std::vector<CompletionItem>>)> Callback,
219 PathRef File, Position Pos, llvm::Optional<StringRef> OverridenContents,
220 IntrusiveRefCntPtr<vfs::FileSystem> *UsedFS) {
221 using CallbackType =
222 UniqueFunction<void(Tagged<std::vector<CompletionItem>>)>;
223
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000224 std::string Contents;
225 if (OverridenContents) {
226 Contents = *OverridenContents;
227 } else {
Ilya Biryukov0e27ce42017-06-13 14:15:56 +0000228 auto FileContents = DraftMgr.getDraft(File);
229 assert(FileContents.Draft &&
230 "codeComplete is called for non-added document");
231
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000232 Contents = std::move(*FileContents.Draft);
Ilya Biryukov0e27ce42017-06-13 14:15:56 +0000233 }
Ilya Biryukov38d79772017-05-16 09:38:59 +0000234
Ilya Biryukovaf0c04b2017-06-14 09:46:44 +0000235 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
Ilya Biryukoved99e4c2017-07-31 17:09:29 +0000236 if (UsedFS)
237 *UsedFS = TaggedFS.Value;
238
Ilya Biryukov02d58702017-08-01 15:51:38 +0000239 std::shared_ptr<CppFile> Resources = Units.getFile(File);
240 assert(Resources && "Calling completion on non-added file");
241
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000242 // Remember the current Preamble and use it when async task starts executing.
243 // At the point when async task starts executing, we may have a different
244 // Preamble in Resources. However, we assume the Preamble that we obtain here
245 // is reusable in completion more often.
246 std::shared_ptr<const PreambleData> Preamble =
247 Resources->getPossiblyStalePreamble();
248 // A task that will be run asynchronously.
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000249 auto Task =
250 // 'mutable' to reassign Preamble variable.
251 [=](CallbackType Callback) mutable {
252 if (!Preamble) {
253 // Maybe we built some preamble before processing this request.
254 Preamble = Resources->getPossiblyStalePreamble();
255 }
256 // FIXME(ibiryukov): even if Preamble is non-null, we may want to check
257 // both the old and the new version in case only one of them matches.
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000258
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000259 std::vector<CompletionItem> Result = clangd::codeComplete(
260 File, Resources->getCompileCommand(),
261 Preamble ? &Preamble->Preamble : nullptr, Contents, Pos,
262 TaggedFS.Value, PCHs, CodeCompleteOpts, Logger);
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000263
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000264 Callback(make_tagged(std::move(Result), std::move(TaggedFS.Tag)));
265 };
266
267 WorkScheduler.addToFront(std::move(Task), std::move(Callback));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000268}
Ilya Biryukovf01af682017-05-23 13:42:59 +0000269
Benjamin Krameree19f162017-10-26 12:28:13 +0000270llvm::Expected<Tagged<SignatureHelp>>
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000271ClangdServer::signatureHelp(PathRef File, Position Pos,
272 llvm::Optional<StringRef> OverridenContents,
273 IntrusiveRefCntPtr<vfs::FileSystem> *UsedFS) {
274 std::string DraftStorage;
275 if (!OverridenContents) {
276 auto FileContents = DraftMgr.getDraft(File);
Benjamin Krameree19f162017-10-26 12:28:13 +0000277 if (!FileContents.Draft)
278 return llvm::make_error<llvm::StringError>(
279 "signatureHelp is called for non-added document",
280 llvm::errc::invalid_argument);
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000281
282 DraftStorage = std::move(*FileContents.Draft);
283 OverridenContents = DraftStorage;
284 }
285
286 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
287 if (UsedFS)
288 *UsedFS = TaggedFS.Value;
289
290 std::shared_ptr<CppFile> Resources = Units.getFile(File);
Benjamin Krameree19f162017-10-26 12:28:13 +0000291 if (!Resources)
292 return llvm::make_error<llvm::StringError>(
293 "signatureHelp is called for non-added document",
294 llvm::errc::invalid_argument);
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000295
296 auto Preamble = Resources->getPossiblyStalePreamble();
297 auto Result = clangd::signatureHelp(File, Resources->getCompileCommand(),
298 Preamble ? &Preamble->Preamble : nullptr,
299 *OverridenContents, Pos, TaggedFS.Value,
300 PCHs, Logger);
301 return make_tagged(std::move(Result), TaggedFS.Tag);
302}
303
Ilya Biryukovafb55542017-05-16 14:40:30 +0000304std::vector<tooling::Replacement> ClangdServer::formatRange(PathRef File,
305 Range Rng) {
306 std::string Code = getDocument(File);
307
308 size_t Begin = positionToOffset(Code, Rng.start);
309 size_t Len = positionToOffset(Code, Rng.end) - Begin;
310 return formatCode(Code, File, {tooling::Range(Begin, Len)});
311}
312
313std::vector<tooling::Replacement> ClangdServer::formatFile(PathRef File) {
314 // Format everything.
315 std::string Code = getDocument(File);
316 return formatCode(Code, File, {tooling::Range(0, Code.size())});
317}
318
319std::vector<tooling::Replacement> ClangdServer::formatOnType(PathRef File,
320 Position Pos) {
321 // Look for the previous opening brace from the character position and
322 // format starting from there.
323 std::string Code = getDocument(File);
324 size_t CursorPos = positionToOffset(Code, Pos);
325 size_t PreviousLBracePos = StringRef(Code).find_last_of('{', CursorPos);
326 if (PreviousLBracePos == StringRef::npos)
327 PreviousLBracePos = CursorPos;
328 size_t Len = 1 + CursorPos - PreviousLBracePos;
329
330 return formatCode(Code, File, {tooling::Range(PreviousLBracePos, Len)});
331}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000332
333std::string ClangdServer::getDocument(PathRef File) {
334 auto draft = DraftMgr.getDraft(File);
335 assert(draft.Draft && "File is not tracked, cannot get contents");
336 return *draft.Draft;
337}
338
Ilya Biryukovf01af682017-05-23 13:42:59 +0000339std::string ClangdServer::dumpAST(PathRef File) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000340 std::shared_ptr<CppFile> Resources = Units.getFile(File);
341 assert(Resources && "dumpAST is called for non-added document");
Ilya Biryukov38d79772017-05-16 09:38:59 +0000342
Ilya Biryukov02d58702017-08-01 15:51:38 +0000343 std::string Result;
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +0000344 Resources->getAST().get()->runUnderLock([&Result](ParsedAST *AST) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000345 llvm::raw_string_ostream ResultOS(Result);
346 if (AST) {
347 clangd::dumpAST(*AST, ResultOS);
348 } else {
349 ResultOS << "<no-ast>";
350 }
351 ResultOS.flush();
Ilya Biryukovf01af682017-05-23 13:42:59 +0000352 });
Ilya Biryukov02d58702017-08-01 15:51:38 +0000353 return Result;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000354}
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000355
Benjamin Krameree19f162017-10-26 12:28:13 +0000356llvm::Expected<Tagged<std::vector<Location>>>
357ClangdServer::findDefinitions(PathRef File, Position Pos) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000358 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
359
360 std::shared_ptr<CppFile> Resources = Units.getFile(File);
Benjamin Krameree19f162017-10-26 12:28:13 +0000361 if (!Resources)
362 return llvm::make_error<llvm::StringError>(
363 "findDefinitions called on non-added file",
364 llvm::errc::invalid_argument);
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000365
366 std::vector<Location> Result;
Ilya Biryukove5128f72017-09-20 07:24:15 +0000367 Resources->getAST().get()->runUnderLock([Pos, &Result, this](ParsedAST *AST) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000368 if (!AST)
369 return;
Ilya Biryukove5128f72017-09-20 07:24:15 +0000370 Result = clangd::findDefinitions(*AST, Pos, Logger);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000371 });
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000372 return make_tagged(std::move(Result), TaggedFS.Tag);
373}
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000374
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000375llvm::Optional<Path> ClangdServer::switchSourceHeader(PathRef Path) {
376
377 StringRef SourceExtensions[] = {".cpp", ".c", ".cc", ".cxx",
378 ".c++", ".m", ".mm"};
379 StringRef HeaderExtensions[] = {".h", ".hh", ".hpp", ".hxx", ".inc"};
380
381 StringRef PathExt = llvm::sys::path::extension(Path);
382
383 // Lookup in a list of known extensions.
384 auto SourceIter =
385 std::find_if(std::begin(SourceExtensions), std::end(SourceExtensions),
386 [&PathExt](PathRef SourceExt) {
387 return SourceExt.equals_lower(PathExt);
388 });
389 bool IsSource = SourceIter != std::end(SourceExtensions);
390
391 auto HeaderIter =
392 std::find_if(std::begin(HeaderExtensions), std::end(HeaderExtensions),
393 [&PathExt](PathRef HeaderExt) {
394 return HeaderExt.equals_lower(PathExt);
395 });
396
397 bool IsHeader = HeaderIter != std::end(HeaderExtensions);
398
399 // We can only switch between extensions known extensions.
400 if (!IsSource && !IsHeader)
401 return llvm::None;
402
403 // Array to lookup extensions for the switch. An opposite of where original
404 // extension was found.
405 ArrayRef<StringRef> NewExts;
406 if (IsSource)
407 NewExts = HeaderExtensions;
408 else
409 NewExts = SourceExtensions;
410
411 // Storage for the new path.
412 SmallString<128> NewPath = StringRef(Path);
413
414 // Instance of vfs::FileSystem, used for file existence checks.
415 auto FS = FSProvider.getTaggedFileSystem(Path).Value;
416
417 // Loop through switched extension candidates.
418 for (StringRef NewExt : NewExts) {
419 llvm::sys::path::replace_extension(NewPath, NewExt);
420 if (FS->exists(NewPath))
421 return NewPath.str().str(); // First str() to convert from SmallString to
422 // StringRef, second to convert from StringRef
423 // to std::string
Ilya Biryukov33334942017-10-06 14:39:39 +0000424
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000425 // Also check NewExt in upper-case, just in case.
426 llvm::sys::path::replace_extension(NewPath, NewExt.upper());
427 if (FS->exists(NewPath))
428 return NewPath.str().str();
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000429 }
430
431 return llvm::None;
432}
433
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000434std::future<void> ClangdServer::scheduleReparseAndDiags(
435 PathRef File, VersionedDraft Contents, std::shared_ptr<CppFile> Resources,
436 Tagged<IntrusiveRefCntPtr<vfs::FileSystem>> TaggedFS) {
437
438 assert(Contents.Draft && "Draft must have contents");
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000439 UniqueFunction<llvm::Optional<std::vector<DiagWithFixIts>>()>
440 DeferredRebuild =
441 Resources->deferRebuild(*Contents.Draft, TaggedFS.Value);
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000442 std::promise<void> DonePromise;
443 std::future<void> DoneFuture = DonePromise.get_future();
444
445 DocVersion Version = Contents.Version;
446 Path FileStr = File;
447 VFSTag Tag = TaggedFS.Tag;
448 auto ReparseAndPublishDiags =
449 [this, FileStr, Version,
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000450 Tag](UniqueFunction<llvm::Optional<std::vector<DiagWithFixIts>>()>
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000451 DeferredRebuild,
452 std::promise<void> DonePromise) -> void {
453 FulfillPromiseGuard Guard(DonePromise);
454
455 auto CurrentVersion = DraftMgr.getVersion(FileStr);
456 if (CurrentVersion != Version)
457 return; // This request is outdated
458
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000459 auto Diags = DeferredRebuild();
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000460 if (!Diags)
461 return; // A new reparse was requested before this one completed.
Ilya Biryukov47f22022017-09-20 12:58:55 +0000462
463 // We need to serialize access to resulting diagnostics to avoid calling
464 // `onDiagnosticsReady` in the wrong order.
465 std::lock_guard<std::mutex> DiagsLock(DiagnosticsMutex);
466 DocVersion &LastReportedDiagsVersion = ReportedDiagnosticVersions[FileStr];
467 // FIXME(ibiryukov): get rid of '<' comparison here. In the current
468 // implementation diagnostics will not be reported after version counters'
469 // overflow. This should not happen in practice, since DocVersion is a
470 // 64-bit unsigned integer.
471 if (Version < LastReportedDiagsVersion)
472 return;
473 LastReportedDiagsVersion = Version;
474
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000475 DiagConsumer.onDiagnosticsReady(FileStr,
476 make_tagged(std::move(*Diags), Tag));
477 };
478
479 WorkScheduler.addToFront(std::move(ReparseAndPublishDiags),
480 std::move(DeferredRebuild), std::move(DonePromise));
481 return DoneFuture;
482}
483
484std::future<void>
485ClangdServer::scheduleCancelRebuild(std::shared_ptr<CppFile> Resources) {
486 std::promise<void> DonePromise;
487 std::future<void> DoneFuture = DonePromise.get_future();
488 if (!Resources) {
489 // No need to schedule any cleanup.
490 DonePromise.set_value();
491 return DoneFuture;
492 }
493
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000494 UniqueFunction<void()> DeferredCancel = Resources->deferCancelRebuild();
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000495 auto CancelReparses = [Resources](std::promise<void> DonePromise,
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000496 UniqueFunction<void()> DeferredCancel) {
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000497 FulfillPromiseGuard Guard(DonePromise);
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000498 DeferredCancel();
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000499 };
500 WorkScheduler.addToFront(std::move(CancelReparses), std::move(DonePromise),
501 std::move(DeferredCancel));
502 return DoneFuture;
503}
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000504
505void ClangdServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
506 // FIXME: Do nothing for now. This will be used for indexing and potentially
507 // invalidating other caches.
508}