blob: ba9336fd36bd06801043db8013d7345925d2f256 [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"
Sam McCall8567cb32017-11-02 09:21:51 +000018#include "llvm/Support/FormatProviders.h"
19#include "llvm/Support/FormatVariadic.h"
Marc-Andre Laperle37de9712017-09-27 15:31:17 +000020#include "llvm/Support/Path.h"
Ilya Biryukovf01af682017-05-23 13:42:59 +000021#include "llvm/Support/raw_ostream.h"
22#include <future>
Ilya Biryukov38d79772017-05-16 09:38:59 +000023
Ilya Biryukov2f314102017-05-16 10:06:20 +000024using namespace clang;
Ilya Biryukov38d79772017-05-16 09:38:59 +000025using namespace clang::clangd;
26
Ilya Biryukovafb55542017-05-16 14:40:30 +000027namespace {
28
Ilya Biryukov02d58702017-08-01 15:51:38 +000029class FulfillPromiseGuard {
30public:
31 FulfillPromiseGuard(std::promise<void> &Promise) : Promise(Promise) {}
32
33 ~FulfillPromiseGuard() { Promise.set_value(); }
34
35private:
36 std::promise<void> &Promise;
37};
38
Ilya Biryukovafb55542017-05-16 14:40:30 +000039std::vector<tooling::Replacement> formatCode(StringRef Code, StringRef Filename,
40 ArrayRef<tooling::Range> Ranges) {
41 // Call clang-format.
42 // FIXME: Don't ignore style.
43 format::FormatStyle Style = format::getLLVMStyle();
44 auto Result = format::reformat(Style, Code, Ranges, Filename);
45
46 return std::vector<tooling::Replacement>(Result.begin(), Result.end());
47}
48
Ilya Biryukova46f7a92017-06-28 10:34:50 +000049std::string getStandardResourceDir() {
50 static int Dummy; // Just an address in this process.
51 return CompilerInvocation::GetResourcesPath("clangd", (void *)&Dummy);
52}
53
Ilya Biryukovafb55542017-05-16 14:40:30 +000054} // namespace
55
56size_t clangd::positionToOffset(StringRef Code, Position P) {
57 size_t Offset = 0;
58 for (int I = 0; I != P.line; ++I) {
59 // FIXME: \r\n
60 // FIXME: UTF-8
61 size_t F = Code.find('\n', Offset);
62 if (F == StringRef::npos)
63 return 0; // FIXME: Is this reasonable?
64 Offset = F + 1;
65 }
66 return (Offset == 0 ? 0 : (Offset - 1)) + P.character;
67}
68
69/// Turn an offset in Code into a [line, column] pair.
70Position clangd::offsetToPosition(StringRef Code, size_t Offset) {
71 StringRef JustBefore = Code.substr(0, Offset);
72 // FIXME: \r\n
73 // FIXME: UTF-8
74 int Lines = JustBefore.count('\n');
75 int Cols = JustBefore.size() - JustBefore.rfind('\n') - 1;
76 return {Lines, Cols};
77}
78
Ilya Biryukov22602992017-05-30 15:11:02 +000079Tagged<IntrusiveRefCntPtr<vfs::FileSystem>>
Ilya Biryukovaf0c04b2017-06-14 09:46:44 +000080RealFileSystemProvider::getTaggedFileSystem(PathRef File) {
Ilya Biryukov22602992017-05-30 15:11:02 +000081 return make_tagged(vfs::getRealFileSystem(), VFSTag());
Ilya Biryukov0f62ed22017-05-26 12:26:51 +000082}
83
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +000084unsigned clangd::getDefaultAsyncThreadsCount() {
85 unsigned HardwareConcurrency = std::thread::hardware_concurrency();
86 // C++ standard says that hardware_concurrency()
87 // may return 0, fallback to 1 worker thread in
88 // that case.
89 if (HardwareConcurrency == 0)
90 return 1;
91 return HardwareConcurrency;
92}
93
94ClangdScheduler::ClangdScheduler(unsigned AsyncThreadsCount)
95 : RunSynchronously(AsyncThreadsCount == 0) {
Ilya Biryukov38d79772017-05-16 09:38:59 +000096 if (RunSynchronously) {
97 // Don't start the worker thread if we're running synchronously
98 return;
99 }
100
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000101 Workers.reserve(AsyncThreadsCount);
102 for (unsigned I = 0; I < AsyncThreadsCount; ++I) {
Sam McCall8567cb32017-11-02 09:21:51 +0000103 Workers.push_back(std::thread([this, I]() {
104 llvm::set_thread_name(llvm::formatv("scheduler/{0}", I));
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000105 while (true) {
Ilya Biryukov08e6ccb2017-10-09 16:26:26 +0000106 UniqueFunction<void()> Request;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000107
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000108 // Pick request from the queue
109 {
110 std::unique_lock<std::mutex> Lock(Mutex);
111 // Wait for more requests.
112 RequestCV.wait(Lock,
113 [this] { return !RequestQueue.empty() || Done; });
114 if (Done)
115 return;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000116
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000117 assert(!RequestQueue.empty() && "RequestQueue was empty");
Ilya Biryukov38d79772017-05-16 09:38:59 +0000118
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000119 // We process requests starting from the front of the queue. Users of
120 // ClangdScheduler have a way to prioritise their requests by putting
121 // them to the either side of the queue (using either addToEnd or
122 // addToFront).
123 Request = std::move(RequestQueue.front());
124 RequestQueue.pop_front();
125 } // unlock Mutex
Ilya Biryukov38d79772017-05-16 09:38:59 +0000126
Ilya Biryukov08e6ccb2017-10-09 16:26:26 +0000127 Request();
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000128 }
129 }));
130 }
Ilya Biryukov38d79772017-05-16 09:38:59 +0000131}
132
133ClangdScheduler::~ClangdScheduler() {
134 if (RunSynchronously)
135 return; // no worker thread is running in that case
136
137 {
138 std::lock_guard<std::mutex> Lock(Mutex);
139 // Wake up the worker thread
140 Done = true;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000141 } // unlock Mutex
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000142 RequestCV.notify_all();
143
144 for (auto &Worker : Workers)
145 Worker.join();
Ilya Biryukov38d79772017-05-16 09:38:59 +0000146}
147
Ilya Biryukov103c9512017-06-13 15:59:43 +0000148ClangdServer::ClangdServer(GlobalCompilationDatabase &CDB,
149 DiagnosticsConsumer &DiagConsumer,
150 FileSystemProvider &FSProvider,
Ilya Biryukovb080cb12017-10-23 14:46:48 +0000151 unsigned AsyncThreadsCount,
152 clangd::CodeCompleteOptions CodeCompleteOpts,
Ilya Biryukove5128f72017-09-20 07:24:15 +0000153 clangd::Logger &Logger,
Ilya Biryukova46f7a92017-06-28 10:34:50 +0000154 llvm::Optional<StringRef> ResourceDir)
Ilya Biryukove5128f72017-09-20 07:24:15 +0000155 : Logger(Logger), CDB(CDB), DiagConsumer(DiagConsumer),
156 FSProvider(FSProvider),
Ilya Biryukova46f7a92017-06-28 10:34:50 +0000157 ResourceDir(ResourceDir ? ResourceDir->str() : getStandardResourceDir()),
Ilya Biryukov38d79772017-05-16 09:38:59 +0000158 PCHs(std::make_shared<PCHContainerOperations>()),
Ilya Biryukovb080cb12017-10-23 14:46:48 +0000159 CodeCompleteOpts(CodeCompleteOpts), WorkScheduler(AsyncThreadsCount) {}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000160
Marc-Andre Laperle37de9712017-09-27 15:31:17 +0000161void ClangdServer::setRootPath(PathRef RootPath) {
162 std::string NewRootPath = llvm::sys::path::convert_to_slash(
163 RootPath, llvm::sys::path::Style::posix);
164 if (llvm::sys::fs::is_directory(NewRootPath))
165 this->RootPath = NewRootPath;
166}
167
Ilya Biryukov02d58702017-08-01 15:51:38 +0000168std::future<void> ClangdServer::addDocument(PathRef File, StringRef Contents) {
Ilya Biryukovf01af682017-05-23 13:42:59 +0000169 DocVersion Version = DraftMgr.updateDraft(File, Contents);
Ilya Biryukovf01af682017-05-23 13:42:59 +0000170
Ilya Biryukov02d58702017-08-01 15:51:38 +0000171 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
Benjamin Kramer5349eed2017-10-28 17:32:56 +0000172 std::shared_ptr<CppFile> Resources =
173 Units.getOrCreateFile(File, ResourceDir, CDB, PCHs, Logger);
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000174 return scheduleReparseAndDiags(File, VersionedDraft{Version, Contents.str()},
175 std::move(Resources), std::move(TaggedFS));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000176}
177
Ilya Biryukov02d58702017-08-01 15:51:38 +0000178std::future<void> ClangdServer::removeDocument(PathRef File) {
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000179 DraftMgr.removeDraft(File);
180 std::shared_ptr<CppFile> Resources = Units.removeIfPresent(File);
181 return scheduleCancelRebuild(std::move(Resources));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000182}
183
Ilya Biryukov02d58702017-08-01 15:51:38 +0000184std::future<void> ClangdServer::forceReparse(PathRef File) {
Ilya Biryukov91dbf5b2017-08-14 08:37:32 +0000185 auto FileContents = DraftMgr.getDraft(File);
186 assert(FileContents.Draft &&
187 "forceReparse() was called for non-added document");
188
189 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
Benjamin Kramer5349eed2017-10-28 17:32:56 +0000190 auto Recreated = Units.recreateFileIfCompileCommandChanged(File, ResourceDir,
191 CDB, PCHs, Logger);
Ilya Biryukov91dbf5b2017-08-14 08:37:32 +0000192
193 // Note that std::future from this cleanup action is ignored.
194 scheduleCancelRebuild(std::move(Recreated.RemovedFile));
195 // Schedule a reparse.
196 return scheduleReparseAndDiags(File, std::move(FileContents),
197 std::move(Recreated.FileInCollection),
198 std::move(TaggedFS));
Ilya Biryukov0f62ed22017-05-26 12:26:51 +0000199}
200
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000201std::future<Tagged<std::vector<CompletionItem>>>
Ilya Biryukov0e27ce42017-06-13 14:15:56 +0000202ClangdServer::codeComplete(PathRef File, Position Pos,
Ilya Biryukoved99e4c2017-07-31 17:09:29 +0000203 llvm::Optional<StringRef> OverridenContents,
204 IntrusiveRefCntPtr<vfs::FileSystem> *UsedFS) {
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000205 using ResultType = Tagged<std::vector<CompletionItem>>;
206
207 std::promise<ResultType> ResultPromise;
208
209 auto Callback = [](std::promise<ResultType> ResultPromise,
210 ResultType Result) -> void {
211 ResultPromise.set_value(std::move(Result));
212 };
213
214 std::future<ResultType> ResultFuture = ResultPromise.get_future();
215 codeComplete(BindWithForward(Callback, std::move(ResultPromise)), File, Pos,
216 OverridenContents, UsedFS);
217 return ResultFuture;
218}
219
220void ClangdServer::codeComplete(
221 UniqueFunction<void(Tagged<std::vector<CompletionItem>>)> Callback,
222 PathRef File, Position Pos, llvm::Optional<StringRef> OverridenContents,
223 IntrusiveRefCntPtr<vfs::FileSystem> *UsedFS) {
224 using CallbackType =
225 UniqueFunction<void(Tagged<std::vector<CompletionItem>>)>;
226
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000227 std::string Contents;
228 if (OverridenContents) {
229 Contents = *OverridenContents;
230 } else {
Ilya Biryukov0e27ce42017-06-13 14:15:56 +0000231 auto FileContents = DraftMgr.getDraft(File);
232 assert(FileContents.Draft &&
233 "codeComplete is called for non-added document");
234
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000235 Contents = std::move(*FileContents.Draft);
Ilya Biryukov0e27ce42017-06-13 14:15:56 +0000236 }
Ilya Biryukov38d79772017-05-16 09:38:59 +0000237
Ilya Biryukovaf0c04b2017-06-14 09:46:44 +0000238 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
Ilya Biryukoved99e4c2017-07-31 17:09:29 +0000239 if (UsedFS)
240 *UsedFS = TaggedFS.Value;
241
Ilya Biryukov02d58702017-08-01 15:51:38 +0000242 std::shared_ptr<CppFile> Resources = Units.getFile(File);
243 assert(Resources && "Calling completion on non-added file");
244
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000245 // Remember the current Preamble and use it when async task starts executing.
246 // At the point when async task starts executing, we may have a different
247 // Preamble in Resources. However, we assume the Preamble that we obtain here
248 // is reusable in completion more often.
249 std::shared_ptr<const PreambleData> Preamble =
250 Resources->getPossiblyStalePreamble();
251 // A task that will be run asynchronously.
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000252 auto Task =
253 // 'mutable' to reassign Preamble variable.
254 [=](CallbackType Callback) mutable {
255 if (!Preamble) {
256 // Maybe we built some preamble before processing this request.
257 Preamble = Resources->getPossiblyStalePreamble();
258 }
259 // FIXME(ibiryukov): even if Preamble is non-null, we may want to check
260 // both the old and the new version in case only one of them matches.
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000261
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000262 std::vector<CompletionItem> Result = clangd::codeComplete(
263 File, Resources->getCompileCommand(),
264 Preamble ? &Preamble->Preamble : nullptr, Contents, Pos,
265 TaggedFS.Value, PCHs, CodeCompleteOpts, Logger);
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000266
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000267 Callback(make_tagged(std::move(Result), std::move(TaggedFS.Tag)));
268 };
269
270 WorkScheduler.addToFront(std::move(Task), std::move(Callback));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000271}
Ilya Biryukovf01af682017-05-23 13:42:59 +0000272
Benjamin Krameree19f162017-10-26 12:28:13 +0000273llvm::Expected<Tagged<SignatureHelp>>
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000274ClangdServer::signatureHelp(PathRef File, Position Pos,
275 llvm::Optional<StringRef> OverridenContents,
276 IntrusiveRefCntPtr<vfs::FileSystem> *UsedFS) {
277 std::string DraftStorage;
278 if (!OverridenContents) {
279 auto FileContents = DraftMgr.getDraft(File);
Benjamin Krameree19f162017-10-26 12:28:13 +0000280 if (!FileContents.Draft)
281 return llvm::make_error<llvm::StringError>(
282 "signatureHelp is called for non-added document",
283 llvm::errc::invalid_argument);
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000284
285 DraftStorage = std::move(*FileContents.Draft);
286 OverridenContents = DraftStorage;
287 }
288
289 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
290 if (UsedFS)
291 *UsedFS = TaggedFS.Value;
292
293 std::shared_ptr<CppFile> Resources = Units.getFile(File);
Benjamin Krameree19f162017-10-26 12:28:13 +0000294 if (!Resources)
295 return llvm::make_error<llvm::StringError>(
296 "signatureHelp is called for non-added document",
297 llvm::errc::invalid_argument);
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000298
299 auto Preamble = Resources->getPossiblyStalePreamble();
300 auto Result = clangd::signatureHelp(File, Resources->getCompileCommand(),
301 Preamble ? &Preamble->Preamble : nullptr,
302 *OverridenContents, Pos, TaggedFS.Value,
303 PCHs, Logger);
304 return make_tagged(std::move(Result), TaggedFS.Tag);
305}
306
Ilya Biryukovafb55542017-05-16 14:40:30 +0000307std::vector<tooling::Replacement> ClangdServer::formatRange(PathRef File,
308 Range Rng) {
309 std::string Code = getDocument(File);
310
311 size_t Begin = positionToOffset(Code, Rng.start);
312 size_t Len = positionToOffset(Code, Rng.end) - Begin;
313 return formatCode(Code, File, {tooling::Range(Begin, Len)});
314}
315
316std::vector<tooling::Replacement> ClangdServer::formatFile(PathRef File) {
317 // Format everything.
318 std::string Code = getDocument(File);
319 return formatCode(Code, File, {tooling::Range(0, Code.size())});
320}
321
322std::vector<tooling::Replacement> ClangdServer::formatOnType(PathRef File,
323 Position Pos) {
324 // Look for the previous opening brace from the character position and
325 // format starting from there.
326 std::string Code = getDocument(File);
327 size_t CursorPos = positionToOffset(Code, Pos);
328 size_t PreviousLBracePos = StringRef(Code).find_last_of('{', CursorPos);
329 if (PreviousLBracePos == StringRef::npos)
330 PreviousLBracePos = CursorPos;
331 size_t Len = 1 + CursorPos - PreviousLBracePos;
332
333 return formatCode(Code, File, {tooling::Range(PreviousLBracePos, Len)});
334}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000335
336std::string ClangdServer::getDocument(PathRef File) {
337 auto draft = DraftMgr.getDraft(File);
338 assert(draft.Draft && "File is not tracked, cannot get contents");
339 return *draft.Draft;
340}
341
Ilya Biryukovf01af682017-05-23 13:42:59 +0000342std::string ClangdServer::dumpAST(PathRef File) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000343 std::shared_ptr<CppFile> Resources = Units.getFile(File);
344 assert(Resources && "dumpAST is called for non-added document");
Ilya Biryukov38d79772017-05-16 09:38:59 +0000345
Ilya Biryukov02d58702017-08-01 15:51:38 +0000346 std::string Result;
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +0000347 Resources->getAST().get()->runUnderLock([&Result](ParsedAST *AST) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000348 llvm::raw_string_ostream ResultOS(Result);
349 if (AST) {
350 clangd::dumpAST(*AST, ResultOS);
351 } else {
352 ResultOS << "<no-ast>";
353 }
354 ResultOS.flush();
Ilya Biryukovf01af682017-05-23 13:42:59 +0000355 });
Ilya Biryukov02d58702017-08-01 15:51:38 +0000356 return Result;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000357}
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000358
Benjamin Krameree19f162017-10-26 12:28:13 +0000359llvm::Expected<Tagged<std::vector<Location>>>
360ClangdServer::findDefinitions(PathRef File, Position Pos) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000361 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
362
363 std::shared_ptr<CppFile> Resources = Units.getFile(File);
Benjamin Krameree19f162017-10-26 12:28:13 +0000364 if (!Resources)
365 return llvm::make_error<llvm::StringError>(
366 "findDefinitions called on non-added file",
367 llvm::errc::invalid_argument);
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000368
369 std::vector<Location> Result;
Ilya Biryukove5128f72017-09-20 07:24:15 +0000370 Resources->getAST().get()->runUnderLock([Pos, &Result, this](ParsedAST *AST) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000371 if (!AST)
372 return;
Ilya Biryukove5128f72017-09-20 07:24:15 +0000373 Result = clangd::findDefinitions(*AST, Pos, Logger);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000374 });
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000375 return make_tagged(std::move(Result), TaggedFS.Tag);
376}
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000377
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000378llvm::Optional<Path> ClangdServer::switchSourceHeader(PathRef Path) {
379
380 StringRef SourceExtensions[] = {".cpp", ".c", ".cc", ".cxx",
381 ".c++", ".m", ".mm"};
382 StringRef HeaderExtensions[] = {".h", ".hh", ".hpp", ".hxx", ".inc"};
383
384 StringRef PathExt = llvm::sys::path::extension(Path);
385
386 // Lookup in a list of known extensions.
387 auto SourceIter =
388 std::find_if(std::begin(SourceExtensions), std::end(SourceExtensions),
389 [&PathExt](PathRef SourceExt) {
390 return SourceExt.equals_lower(PathExt);
391 });
392 bool IsSource = SourceIter != std::end(SourceExtensions);
393
394 auto HeaderIter =
395 std::find_if(std::begin(HeaderExtensions), std::end(HeaderExtensions),
396 [&PathExt](PathRef HeaderExt) {
397 return HeaderExt.equals_lower(PathExt);
398 });
399
400 bool IsHeader = HeaderIter != std::end(HeaderExtensions);
401
402 // We can only switch between extensions known extensions.
403 if (!IsSource && !IsHeader)
404 return llvm::None;
405
406 // Array to lookup extensions for the switch. An opposite of where original
407 // extension was found.
408 ArrayRef<StringRef> NewExts;
409 if (IsSource)
410 NewExts = HeaderExtensions;
411 else
412 NewExts = SourceExtensions;
413
414 // Storage for the new path.
415 SmallString<128> NewPath = StringRef(Path);
416
417 // Instance of vfs::FileSystem, used for file existence checks.
418 auto FS = FSProvider.getTaggedFileSystem(Path).Value;
419
420 // Loop through switched extension candidates.
421 for (StringRef NewExt : NewExts) {
422 llvm::sys::path::replace_extension(NewPath, NewExt);
423 if (FS->exists(NewPath))
424 return NewPath.str().str(); // First str() to convert from SmallString to
425 // StringRef, second to convert from StringRef
426 // to std::string
Ilya Biryukov33334942017-10-06 14:39:39 +0000427
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000428 // Also check NewExt in upper-case, just in case.
429 llvm::sys::path::replace_extension(NewPath, NewExt.upper());
430 if (FS->exists(NewPath))
431 return NewPath.str().str();
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000432 }
433
434 return llvm::None;
435}
436
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000437std::future<void> ClangdServer::scheduleReparseAndDiags(
438 PathRef File, VersionedDraft Contents, std::shared_ptr<CppFile> Resources,
439 Tagged<IntrusiveRefCntPtr<vfs::FileSystem>> TaggedFS) {
440
441 assert(Contents.Draft && "Draft must have contents");
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000442 UniqueFunction<llvm::Optional<std::vector<DiagWithFixIts>>()>
443 DeferredRebuild =
444 Resources->deferRebuild(*Contents.Draft, TaggedFS.Value);
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000445 std::promise<void> DonePromise;
446 std::future<void> DoneFuture = DonePromise.get_future();
447
448 DocVersion Version = Contents.Version;
449 Path FileStr = File;
450 VFSTag Tag = TaggedFS.Tag;
451 auto ReparseAndPublishDiags =
452 [this, FileStr, Version,
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000453 Tag](UniqueFunction<llvm::Optional<std::vector<DiagWithFixIts>>()>
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000454 DeferredRebuild,
455 std::promise<void> DonePromise) -> void {
456 FulfillPromiseGuard Guard(DonePromise);
457
458 auto CurrentVersion = DraftMgr.getVersion(FileStr);
459 if (CurrentVersion != Version)
460 return; // This request is outdated
461
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000462 auto Diags = DeferredRebuild();
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000463 if (!Diags)
464 return; // A new reparse was requested before this one completed.
Ilya Biryukov47f22022017-09-20 12:58:55 +0000465
466 // We need to serialize access to resulting diagnostics to avoid calling
467 // `onDiagnosticsReady` in the wrong order.
468 std::lock_guard<std::mutex> DiagsLock(DiagnosticsMutex);
469 DocVersion &LastReportedDiagsVersion = ReportedDiagnosticVersions[FileStr];
470 // FIXME(ibiryukov): get rid of '<' comparison here. In the current
471 // implementation diagnostics will not be reported after version counters'
472 // overflow. This should not happen in practice, since DocVersion is a
473 // 64-bit unsigned integer.
474 if (Version < LastReportedDiagsVersion)
475 return;
476 LastReportedDiagsVersion = Version;
477
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000478 DiagConsumer.onDiagnosticsReady(FileStr,
479 make_tagged(std::move(*Diags), Tag));
480 };
481
482 WorkScheduler.addToFront(std::move(ReparseAndPublishDiags),
483 std::move(DeferredRebuild), std::move(DonePromise));
484 return DoneFuture;
485}
486
487std::future<void>
488ClangdServer::scheduleCancelRebuild(std::shared_ptr<CppFile> Resources) {
489 std::promise<void> DonePromise;
490 std::future<void> DoneFuture = DonePromise.get_future();
491 if (!Resources) {
492 // No need to schedule any cleanup.
493 DonePromise.set_value();
494 return DoneFuture;
495 }
496
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000497 UniqueFunction<void()> DeferredCancel = Resources->deferCancelRebuild();
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000498 auto CancelReparses = [Resources](std::promise<void> DonePromise,
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000499 UniqueFunction<void()> DeferredCancel) {
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000500 FulfillPromiseGuard Guard(DonePromise);
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000501 DeferredCancel();
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000502 };
503 WorkScheduler.addToFront(std::move(CancelReparses), std::move(DonePromise),
504 std::move(DeferredCancel));
505 return DoneFuture;
506}
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000507
508void ClangdServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
509 // FIXME: Do nothing for now. This will be used for indexing and potentially
510 // invalidating other caches.
511}