blob: 618d69ff253c5fe6b557a250d93735f56e6daa21 [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 Biryukov9e11c4c2017-11-15 18:04:56 +000015#include "clang/Tooling/Refactoring/RefactoringResultConsumer.h"
16#include "clang/Tooling/Refactoring/Rename/RenamingAction.h"
Ilya Biryukovafb55542017-05-16 14:40:30 +000017#include "llvm/ADT/ArrayRef.h"
Benjamin Krameree19f162017-10-26 12:28:13 +000018#include "llvm/Support/Errc.h"
Ilya Biryukov38d79772017-05-16 09:38:59 +000019#include "llvm/Support/FileSystem.h"
Sam McCall8567cb32017-11-02 09:21:51 +000020#include "llvm/Support/FormatProviders.h"
21#include "llvm/Support/FormatVariadic.h"
Marc-Andre Laperle37de9712017-09-27 15:31:17 +000022#include "llvm/Support/Path.h"
Ilya Biryukovf01af682017-05-23 13:42:59 +000023#include "llvm/Support/raw_ostream.h"
24#include <future>
Ilya Biryukov38d79772017-05-16 09:38:59 +000025
Ilya Biryukov2f314102017-05-16 10:06:20 +000026using namespace clang;
Ilya Biryukov38d79772017-05-16 09:38:59 +000027using namespace clang::clangd;
28
Ilya Biryukovafb55542017-05-16 14:40:30 +000029namespace {
30
Ilya Biryukov02d58702017-08-01 15:51:38 +000031class FulfillPromiseGuard {
32public:
33 FulfillPromiseGuard(std::promise<void> &Promise) : Promise(Promise) {}
34
35 ~FulfillPromiseGuard() { Promise.set_value(); }
36
37private:
38 std::promise<void> &Promise;
39};
40
Ilya Biryukovafb55542017-05-16 14:40:30 +000041std::vector<tooling::Replacement> formatCode(StringRef Code, StringRef Filename,
42 ArrayRef<tooling::Range> Ranges) {
43 // Call clang-format.
44 // FIXME: Don't ignore style.
45 format::FormatStyle Style = format::getLLVMStyle();
46 auto Result = format::reformat(Style, Code, Ranges, Filename);
47
48 return std::vector<tooling::Replacement>(Result.begin(), Result.end());
49}
50
Ilya Biryukova46f7a92017-06-28 10:34:50 +000051std::string getStandardResourceDir() {
52 static int Dummy; // Just an address in this process.
53 return CompilerInvocation::GetResourcesPath("clangd", (void *)&Dummy);
54}
55
Haojian Wu345099c2017-11-09 11:30:04 +000056class RefactoringResultCollector final
57 : public tooling::RefactoringResultConsumer {
58public:
59 void handleError(llvm::Error Err) override {
60 assert(!Result.hasValue());
61 // FIXME: figure out a way to return better message for DiagnosticError.
62 // clangd uses llvm::toString to convert the Err to string, however, for
63 // DiagnosticError, only "clang diagnostic" will be generated.
64 Result = std::move(Err);
65 }
66
67 // Using the handle(SymbolOccurrences) from parent class.
68 using tooling::RefactoringResultConsumer::handle;
69
70 void handle(tooling::AtomicChanges SourceReplacements) override {
71 assert(!Result.hasValue());
72 Result = std::move(SourceReplacements);
73 }
74
75 Optional<Expected<tooling::AtomicChanges>> Result;
76};
77
Ilya Biryukovafb55542017-05-16 14:40:30 +000078} // namespace
79
80size_t clangd::positionToOffset(StringRef Code, Position P) {
81 size_t Offset = 0;
82 for (int I = 0; I != P.line; ++I) {
83 // FIXME: \r\n
84 // FIXME: UTF-8
85 size_t F = Code.find('\n', Offset);
86 if (F == StringRef::npos)
87 return 0; // FIXME: Is this reasonable?
88 Offset = F + 1;
89 }
90 return (Offset == 0 ? 0 : (Offset - 1)) + P.character;
91}
92
93/// Turn an offset in Code into a [line, column] pair.
94Position clangd::offsetToPosition(StringRef Code, size_t Offset) {
95 StringRef JustBefore = Code.substr(0, Offset);
96 // FIXME: \r\n
97 // FIXME: UTF-8
98 int Lines = JustBefore.count('\n');
99 int Cols = JustBefore.size() - JustBefore.rfind('\n') - 1;
100 return {Lines, Cols};
101}
102
Ilya Biryukov22602992017-05-30 15:11:02 +0000103Tagged<IntrusiveRefCntPtr<vfs::FileSystem>>
Ilya Biryukovaf0c04b2017-06-14 09:46:44 +0000104RealFileSystemProvider::getTaggedFileSystem(PathRef File) {
Ilya Biryukov22602992017-05-30 15:11:02 +0000105 return make_tagged(vfs::getRealFileSystem(), VFSTag());
Ilya Biryukov0f62ed22017-05-26 12:26:51 +0000106}
107
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000108unsigned clangd::getDefaultAsyncThreadsCount() {
109 unsigned HardwareConcurrency = std::thread::hardware_concurrency();
110 // C++ standard says that hardware_concurrency()
111 // may return 0, fallback to 1 worker thread in
112 // that case.
113 if (HardwareConcurrency == 0)
114 return 1;
115 return HardwareConcurrency;
116}
117
118ClangdScheduler::ClangdScheduler(unsigned AsyncThreadsCount)
119 : RunSynchronously(AsyncThreadsCount == 0) {
Ilya Biryukov38d79772017-05-16 09:38:59 +0000120 if (RunSynchronously) {
121 // Don't start the worker thread if we're running synchronously
122 return;
123 }
124
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000125 Workers.reserve(AsyncThreadsCount);
126 for (unsigned I = 0; I < AsyncThreadsCount; ++I) {
Sam McCall8567cb32017-11-02 09:21:51 +0000127 Workers.push_back(std::thread([this, I]() {
128 llvm::set_thread_name(llvm::formatv("scheduler/{0}", I));
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000129 while (true) {
Ilya Biryukov08e6ccb2017-10-09 16:26:26 +0000130 UniqueFunction<void()> Request;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000131
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000132 // Pick request from the queue
133 {
134 std::unique_lock<std::mutex> Lock(Mutex);
135 // Wait for more requests.
136 RequestCV.wait(Lock,
137 [this] { return !RequestQueue.empty() || Done; });
138 if (Done)
139 return;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000140
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000141 assert(!RequestQueue.empty() && "RequestQueue was empty");
Ilya Biryukov38d79772017-05-16 09:38:59 +0000142
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000143 // We process requests starting from the front of the queue. Users of
144 // ClangdScheduler have a way to prioritise their requests by putting
145 // them to the either side of the queue (using either addToEnd or
146 // addToFront).
147 Request = std::move(RequestQueue.front());
148 RequestQueue.pop_front();
149 } // unlock Mutex
Ilya Biryukov38d79772017-05-16 09:38:59 +0000150
Ilya Biryukov08e6ccb2017-10-09 16:26:26 +0000151 Request();
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000152 }
153 }));
154 }
Ilya Biryukov38d79772017-05-16 09:38:59 +0000155}
156
157ClangdScheduler::~ClangdScheduler() {
158 if (RunSynchronously)
159 return; // no worker thread is running in that case
160
161 {
162 std::lock_guard<std::mutex> Lock(Mutex);
163 // Wake up the worker thread
164 Done = true;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000165 } // unlock Mutex
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000166 RequestCV.notify_all();
167
168 for (auto &Worker : Workers)
169 Worker.join();
Ilya Biryukov38d79772017-05-16 09:38:59 +0000170}
171
Sam McCalladccab62017-11-23 16:58:22 +0000172ClangdServer::ClangdServer(GlobalCompilationDatabase &CDB,
173 DiagnosticsConsumer &DiagConsumer,
174 FileSystemProvider &FSProvider,
175 unsigned AsyncThreadsCount,
176 bool StorePreamblesInMemory,
177 const clangd::CodeCompleteOptions &CodeCompleteOpts,
178 clangd::Logger &Logger,
179 llvm::Optional<StringRef> ResourceDir)
Ilya Biryukove5128f72017-09-20 07:24:15 +0000180 : Logger(Logger), CDB(CDB), DiagConsumer(DiagConsumer),
181 FSProvider(FSProvider),
Ilya Biryukova46f7a92017-06-28 10:34:50 +0000182 ResourceDir(ResourceDir ? ResourceDir->str() : getStandardResourceDir()),
Ilya Biryukov38d79772017-05-16 09:38:59 +0000183 PCHs(std::make_shared<PCHContainerOperations>()),
Ilya Biryukove9eb7f02017-11-16 16:25:18 +0000184 StorePreamblesInMemory(StorePreamblesInMemory),
Ilya Biryukovb080cb12017-10-23 14:46:48 +0000185 CodeCompleteOpts(CodeCompleteOpts), WorkScheduler(AsyncThreadsCount) {}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000186
Marc-Andre Laperle37de9712017-09-27 15:31:17 +0000187void ClangdServer::setRootPath(PathRef RootPath) {
188 std::string NewRootPath = llvm::sys::path::convert_to_slash(
189 RootPath, llvm::sys::path::Style::posix);
190 if (llvm::sys::fs::is_directory(NewRootPath))
191 this->RootPath = NewRootPath;
192}
193
Ilya Biryukov02d58702017-08-01 15:51:38 +0000194std::future<void> ClangdServer::addDocument(PathRef File, StringRef Contents) {
Ilya Biryukovf01af682017-05-23 13:42:59 +0000195 DocVersion Version = DraftMgr.updateDraft(File, Contents);
Ilya Biryukovf01af682017-05-23 13:42:59 +0000196
Ilya Biryukov02d58702017-08-01 15:51:38 +0000197 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
Ilya Biryukove9eb7f02017-11-16 16:25:18 +0000198 std::shared_ptr<CppFile> Resources = Units.getOrCreateFile(
199 File, ResourceDir, CDB, StorePreamblesInMemory, PCHs, Logger);
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000200 return scheduleReparseAndDiags(File, VersionedDraft{Version, Contents.str()},
201 std::move(Resources), std::move(TaggedFS));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000202}
203
Ilya Biryukov02d58702017-08-01 15:51:38 +0000204std::future<void> ClangdServer::removeDocument(PathRef File) {
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000205 DraftMgr.removeDraft(File);
206 std::shared_ptr<CppFile> Resources = Units.removeIfPresent(File);
207 return scheduleCancelRebuild(std::move(Resources));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000208}
209
Ilya Biryukov02d58702017-08-01 15:51:38 +0000210std::future<void> ClangdServer::forceReparse(PathRef File) {
Ilya Biryukov91dbf5b2017-08-14 08:37:32 +0000211 auto FileContents = DraftMgr.getDraft(File);
212 assert(FileContents.Draft &&
213 "forceReparse() was called for non-added document");
214
215 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
Ilya Biryukove9eb7f02017-11-16 16:25:18 +0000216 auto Recreated = Units.recreateFileIfCompileCommandChanged(
217 File, ResourceDir, CDB, StorePreamblesInMemory, PCHs, Logger);
Ilya Biryukov91dbf5b2017-08-14 08:37:32 +0000218
219 // Note that std::future from this cleanup action is ignored.
220 scheduleCancelRebuild(std::move(Recreated.RemovedFile));
221 // Schedule a reparse.
222 return scheduleReparseAndDiags(File, std::move(FileContents),
223 std::move(Recreated.FileInCollection),
224 std::move(TaggedFS));
Ilya Biryukov0f62ed22017-05-26 12:26:51 +0000225}
226
Sam McCalla40371b2017-11-15 09:16:29 +0000227std::future<Tagged<CompletionList>>
Ilya Biryukov0e27ce42017-06-13 14:15:56 +0000228ClangdServer::codeComplete(PathRef File, Position Pos,
Ilya Biryukoved99e4c2017-07-31 17:09:29 +0000229 llvm::Optional<StringRef> OverridenContents,
230 IntrusiveRefCntPtr<vfs::FileSystem> *UsedFS) {
Sam McCalla40371b2017-11-15 09:16:29 +0000231 using ResultType = Tagged<CompletionList>;
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000232
233 std::promise<ResultType> ResultPromise;
234
235 auto Callback = [](std::promise<ResultType> ResultPromise,
236 ResultType Result) -> void {
237 ResultPromise.set_value(std::move(Result));
238 };
239
240 std::future<ResultType> ResultFuture = ResultPromise.get_future();
241 codeComplete(BindWithForward(Callback, std::move(ResultPromise)), File, Pos,
242 OverridenContents, UsedFS);
243 return ResultFuture;
244}
245
246void ClangdServer::codeComplete(
Sam McCalla40371b2017-11-15 09:16:29 +0000247 UniqueFunction<void(Tagged<CompletionList>)> Callback, PathRef File,
248 Position Pos, llvm::Optional<StringRef> OverridenContents,
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000249 IntrusiveRefCntPtr<vfs::FileSystem> *UsedFS) {
Sam McCalla40371b2017-11-15 09:16:29 +0000250 using CallbackType = UniqueFunction<void(Tagged<CompletionList>)>;
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000251
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000252 std::string Contents;
253 if (OverridenContents) {
254 Contents = *OverridenContents;
255 } else {
Ilya Biryukov0e27ce42017-06-13 14:15:56 +0000256 auto FileContents = DraftMgr.getDraft(File);
257 assert(FileContents.Draft &&
258 "codeComplete is called for non-added document");
259
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000260 Contents = std::move(*FileContents.Draft);
Ilya Biryukov0e27ce42017-06-13 14:15:56 +0000261 }
Ilya Biryukov38d79772017-05-16 09:38:59 +0000262
Ilya Biryukovaf0c04b2017-06-14 09:46:44 +0000263 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
Ilya Biryukoved99e4c2017-07-31 17:09:29 +0000264 if (UsedFS)
265 *UsedFS = TaggedFS.Value;
266
Ilya Biryukov02d58702017-08-01 15:51:38 +0000267 std::shared_ptr<CppFile> Resources = Units.getFile(File);
268 assert(Resources && "Calling completion on non-added file");
269
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000270 // Remember the current Preamble and use it when async task starts executing.
271 // At the point when async task starts executing, we may have a different
272 // Preamble in Resources. However, we assume the Preamble that we obtain here
273 // is reusable in completion more often.
274 std::shared_ptr<const PreambleData> Preamble =
275 Resources->getPossiblyStalePreamble();
276 // A task that will be run asynchronously.
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000277 auto Task =
278 // 'mutable' to reassign Preamble variable.
279 [=](CallbackType Callback) mutable {
280 if (!Preamble) {
281 // Maybe we built some preamble before processing this request.
282 Preamble = Resources->getPossiblyStalePreamble();
283 }
284 // FIXME(ibiryukov): even if Preamble is non-null, we may want to check
285 // both the old and the new version in case only one of them matches.
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000286
Sam McCalla40371b2017-11-15 09:16:29 +0000287 CompletionList Result = clangd::codeComplete(
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000288 File, Resources->getCompileCommand(),
289 Preamble ? &Preamble->Preamble : nullptr, Contents, Pos,
290 TaggedFS.Value, PCHs, CodeCompleteOpts, Logger);
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000291
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000292 Callback(make_tagged(std::move(Result), std::move(TaggedFS.Tag)));
293 };
294
295 WorkScheduler.addToFront(std::move(Task), std::move(Callback));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000296}
Ilya Biryukovf01af682017-05-23 13:42:59 +0000297
Benjamin Krameree19f162017-10-26 12:28:13 +0000298llvm::Expected<Tagged<SignatureHelp>>
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000299ClangdServer::signatureHelp(PathRef File, Position Pos,
300 llvm::Optional<StringRef> OverridenContents,
301 IntrusiveRefCntPtr<vfs::FileSystem> *UsedFS) {
302 std::string DraftStorage;
303 if (!OverridenContents) {
304 auto FileContents = DraftMgr.getDraft(File);
Benjamin Krameree19f162017-10-26 12:28:13 +0000305 if (!FileContents.Draft)
306 return llvm::make_error<llvm::StringError>(
307 "signatureHelp is called for non-added document",
308 llvm::errc::invalid_argument);
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000309
310 DraftStorage = std::move(*FileContents.Draft);
311 OverridenContents = DraftStorage;
312 }
313
314 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
315 if (UsedFS)
316 *UsedFS = TaggedFS.Value;
317
318 std::shared_ptr<CppFile> Resources = Units.getFile(File);
Benjamin Krameree19f162017-10-26 12:28:13 +0000319 if (!Resources)
320 return llvm::make_error<llvm::StringError>(
321 "signatureHelp is called for non-added document",
322 llvm::errc::invalid_argument);
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000323
324 auto Preamble = Resources->getPossiblyStalePreamble();
325 auto Result = clangd::signatureHelp(File, Resources->getCompileCommand(),
326 Preamble ? &Preamble->Preamble : nullptr,
327 *OverridenContents, Pos, TaggedFS.Value,
328 PCHs, Logger);
329 return make_tagged(std::move(Result), TaggedFS.Tag);
330}
331
Ilya Biryukovafb55542017-05-16 14:40:30 +0000332std::vector<tooling::Replacement> ClangdServer::formatRange(PathRef File,
333 Range Rng) {
334 std::string Code = getDocument(File);
335
336 size_t Begin = positionToOffset(Code, Rng.start);
337 size_t Len = positionToOffset(Code, Rng.end) - Begin;
338 return formatCode(Code, File, {tooling::Range(Begin, Len)});
339}
340
341std::vector<tooling::Replacement> ClangdServer::formatFile(PathRef File) {
342 // Format everything.
343 std::string Code = getDocument(File);
344 return formatCode(Code, File, {tooling::Range(0, Code.size())});
345}
346
347std::vector<tooling::Replacement> ClangdServer::formatOnType(PathRef File,
348 Position Pos) {
349 // Look for the previous opening brace from the character position and
350 // format starting from there.
351 std::string Code = getDocument(File);
352 size_t CursorPos = positionToOffset(Code, Pos);
353 size_t PreviousLBracePos = StringRef(Code).find_last_of('{', CursorPos);
354 if (PreviousLBracePos == StringRef::npos)
355 PreviousLBracePos = CursorPos;
356 size_t Len = 1 + CursorPos - PreviousLBracePos;
357
358 return formatCode(Code, File, {tooling::Range(PreviousLBracePos, Len)});
359}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000360
Haojian Wu345099c2017-11-09 11:30:04 +0000361Expected<std::vector<tooling::Replacement>>
362ClangdServer::rename(PathRef File, Position Pos, llvm::StringRef NewName) {
363 std::string Code = getDocument(File);
364 std::shared_ptr<CppFile> Resources = Units.getFile(File);
365 RefactoringResultCollector ResultCollector;
366 Resources->getAST().get()->runUnderLock([&](ParsedAST *AST) {
367 const SourceManager &SourceMgr = AST->getASTContext().getSourceManager();
368 const FileEntry *FE =
369 SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
370 if (!FE)
371 return;
372 SourceLocation SourceLocationBeg =
373 clangd::getBeginningOfIdentifier(*AST, Pos, FE);
374 tooling::RefactoringRuleContext Context(
375 AST->getASTContext().getSourceManager());
376 Context.setASTContext(AST->getASTContext());
377 auto Rename = clang::tooling::RenameOccurrences::initiate(
378 Context, SourceRange(SourceLocationBeg), NewName.str());
379 if (!Rename) {
380 ResultCollector.Result = Rename.takeError();
381 return;
382 }
383 Rename->invoke(ResultCollector, Context);
384 });
385 assert(ResultCollector.Result.hasValue());
386 if (!ResultCollector.Result.getValue())
387 return ResultCollector.Result->takeError();
388
389 std::vector<tooling::Replacement> Replacements;
390 for (const tooling::AtomicChange &Change : ResultCollector.Result->get()) {
391 tooling::Replacements ChangeReps = Change.getReplacements();
392 for (const auto &Rep : ChangeReps) {
393 // FIXME: Right now we only support renaming the main file, so we drop
394 // replacements not for the main file. In the future, we might consider to
395 // support:
396 // * rename in any included header
397 // * rename only in the "main" header
398 // * provide an error if there are symbols we won't rename (e.g.
399 // std::vector)
400 // * rename globally in project
401 // * rename in open files
402 if (Rep.getFilePath() == File)
403 Replacements.push_back(Rep);
404 }
405 }
406 return Replacements;
407}
408
Ilya Biryukov38d79772017-05-16 09:38:59 +0000409std::string ClangdServer::getDocument(PathRef File) {
410 auto draft = DraftMgr.getDraft(File);
411 assert(draft.Draft && "File is not tracked, cannot get contents");
412 return *draft.Draft;
413}
414
Ilya Biryukovf01af682017-05-23 13:42:59 +0000415std::string ClangdServer::dumpAST(PathRef File) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000416 std::shared_ptr<CppFile> Resources = Units.getFile(File);
417 assert(Resources && "dumpAST is called for non-added document");
Ilya Biryukov38d79772017-05-16 09:38:59 +0000418
Ilya Biryukov02d58702017-08-01 15:51:38 +0000419 std::string Result;
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +0000420 Resources->getAST().get()->runUnderLock([&Result](ParsedAST *AST) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000421 llvm::raw_string_ostream ResultOS(Result);
422 if (AST) {
423 clangd::dumpAST(*AST, ResultOS);
424 } else {
425 ResultOS << "<no-ast>";
426 }
427 ResultOS.flush();
Ilya Biryukovf01af682017-05-23 13:42:59 +0000428 });
Ilya Biryukov02d58702017-08-01 15:51:38 +0000429 return Result;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000430}
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000431
Benjamin Krameree19f162017-10-26 12:28:13 +0000432llvm::Expected<Tagged<std::vector<Location>>>
433ClangdServer::findDefinitions(PathRef File, Position Pos) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000434 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
435
436 std::shared_ptr<CppFile> Resources = Units.getFile(File);
Benjamin Krameree19f162017-10-26 12:28:13 +0000437 if (!Resources)
438 return llvm::make_error<llvm::StringError>(
439 "findDefinitions called on non-added file",
440 llvm::errc::invalid_argument);
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000441
442 std::vector<Location> Result;
Ilya Biryukove5128f72017-09-20 07:24:15 +0000443 Resources->getAST().get()->runUnderLock([Pos, &Result, this](ParsedAST *AST) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000444 if (!AST)
445 return;
Ilya Biryukove5128f72017-09-20 07:24:15 +0000446 Result = clangd::findDefinitions(*AST, Pos, Logger);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000447 });
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000448 return make_tagged(std::move(Result), TaggedFS.Tag);
449}
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000450
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000451llvm::Optional<Path> ClangdServer::switchSourceHeader(PathRef Path) {
452
453 StringRef SourceExtensions[] = {".cpp", ".c", ".cc", ".cxx",
454 ".c++", ".m", ".mm"};
455 StringRef HeaderExtensions[] = {".h", ".hh", ".hpp", ".hxx", ".inc"};
456
457 StringRef PathExt = llvm::sys::path::extension(Path);
458
459 // Lookup in a list of known extensions.
460 auto SourceIter =
461 std::find_if(std::begin(SourceExtensions), std::end(SourceExtensions),
462 [&PathExt](PathRef SourceExt) {
463 return SourceExt.equals_lower(PathExt);
464 });
465 bool IsSource = SourceIter != std::end(SourceExtensions);
466
467 auto HeaderIter =
468 std::find_if(std::begin(HeaderExtensions), std::end(HeaderExtensions),
469 [&PathExt](PathRef HeaderExt) {
470 return HeaderExt.equals_lower(PathExt);
471 });
472
473 bool IsHeader = HeaderIter != std::end(HeaderExtensions);
474
475 // We can only switch between extensions known extensions.
476 if (!IsSource && !IsHeader)
477 return llvm::None;
478
479 // Array to lookup extensions for the switch. An opposite of where original
480 // extension was found.
481 ArrayRef<StringRef> NewExts;
482 if (IsSource)
483 NewExts = HeaderExtensions;
484 else
485 NewExts = SourceExtensions;
486
487 // Storage for the new path.
488 SmallString<128> NewPath = StringRef(Path);
489
490 // Instance of vfs::FileSystem, used for file existence checks.
491 auto FS = FSProvider.getTaggedFileSystem(Path).Value;
492
493 // Loop through switched extension candidates.
494 for (StringRef NewExt : NewExts) {
495 llvm::sys::path::replace_extension(NewPath, NewExt);
496 if (FS->exists(NewPath))
497 return NewPath.str().str(); // First str() to convert from SmallString to
498 // StringRef, second to convert from StringRef
499 // to std::string
Ilya Biryukov33334942017-10-06 14:39:39 +0000500
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000501 // Also check NewExt in upper-case, just in case.
502 llvm::sys::path::replace_extension(NewPath, NewExt.upper());
503 if (FS->exists(NewPath))
504 return NewPath.str().str();
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000505 }
506
507 return llvm::None;
508}
509
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000510std::future<void> ClangdServer::scheduleReparseAndDiags(
511 PathRef File, VersionedDraft Contents, std::shared_ptr<CppFile> Resources,
512 Tagged<IntrusiveRefCntPtr<vfs::FileSystem>> TaggedFS) {
513
514 assert(Contents.Draft && "Draft must have contents");
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000515 UniqueFunction<llvm::Optional<std::vector<DiagWithFixIts>>()>
516 DeferredRebuild =
517 Resources->deferRebuild(*Contents.Draft, TaggedFS.Value);
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000518 std::promise<void> DonePromise;
519 std::future<void> DoneFuture = DonePromise.get_future();
520
521 DocVersion Version = Contents.Version;
522 Path FileStr = File;
523 VFSTag Tag = TaggedFS.Tag;
524 auto ReparseAndPublishDiags =
525 [this, FileStr, Version,
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000526 Tag](UniqueFunction<llvm::Optional<std::vector<DiagWithFixIts>>()>
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000527 DeferredRebuild,
528 std::promise<void> DonePromise) -> void {
529 FulfillPromiseGuard Guard(DonePromise);
530
531 auto CurrentVersion = DraftMgr.getVersion(FileStr);
532 if (CurrentVersion != Version)
533 return; // This request is outdated
534
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000535 auto Diags = DeferredRebuild();
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000536 if (!Diags)
537 return; // A new reparse was requested before this one completed.
Ilya Biryukov47f22022017-09-20 12:58:55 +0000538
539 // We need to serialize access to resulting diagnostics to avoid calling
540 // `onDiagnosticsReady` in the wrong order.
541 std::lock_guard<std::mutex> DiagsLock(DiagnosticsMutex);
542 DocVersion &LastReportedDiagsVersion = ReportedDiagnosticVersions[FileStr];
543 // FIXME(ibiryukov): get rid of '<' comparison here. In the current
544 // implementation diagnostics will not be reported after version counters'
545 // overflow. This should not happen in practice, since DocVersion is a
546 // 64-bit unsigned integer.
547 if (Version < LastReportedDiagsVersion)
548 return;
549 LastReportedDiagsVersion = Version;
550
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000551 DiagConsumer.onDiagnosticsReady(FileStr,
552 make_tagged(std::move(*Diags), Tag));
553 };
554
555 WorkScheduler.addToFront(std::move(ReparseAndPublishDiags),
556 std::move(DeferredRebuild), std::move(DonePromise));
557 return DoneFuture;
558}
559
560std::future<void>
561ClangdServer::scheduleCancelRebuild(std::shared_ptr<CppFile> Resources) {
562 std::promise<void> DonePromise;
563 std::future<void> DoneFuture = DonePromise.get_future();
564 if (!Resources) {
565 // No need to schedule any cleanup.
566 DonePromise.set_value();
567 return DoneFuture;
568 }
569
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000570 UniqueFunction<void()> DeferredCancel = Resources->deferCancelRebuild();
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000571 auto CancelReparses = [Resources](std::promise<void> DonePromise,
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000572 UniqueFunction<void()> DeferredCancel) {
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000573 FulfillPromiseGuard Guard(DonePromise);
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000574 DeferredCancel();
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000575 };
576 WorkScheduler.addToFront(std::move(CancelReparses), std::move(DonePromise),
577 std::move(DeferredCancel));
578 return DoneFuture;
579}
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000580
581void ClangdServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
582 // FIXME: Do nothing for now. This will be used for indexing and potentially
583 // invalidating other caches.
584}