blob: df85bca9a22fe317ce3f2cf13939d62ad513037a [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"
Haojian Wu345099c2017-11-09 11:30:04 +000012#include "clang/Tooling/Refactoring/RefactoringResultConsumer.h"
13#include "clang/Tooling/Refactoring/Rename/RenamingAction.h"
Ilya Biryukov38d79772017-05-16 09:38:59 +000014#include "clang/Frontend/CompilerInstance.h"
15#include "clang/Frontend/CompilerInvocation.h"
16#include "clang/Tooling/CompilationDatabase.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
Ilya Biryukov103c9512017-06-13 15:59:43 +0000172ClangdServer::ClangdServer(GlobalCompilationDatabase &CDB,
173 DiagnosticsConsumer &DiagConsumer,
174 FileSystemProvider &FSProvider,
Ilya Biryukovb080cb12017-10-23 14:46:48 +0000175 unsigned AsyncThreadsCount,
176 clangd::CodeCompleteOptions CodeCompleteOpts,
Ilya Biryukove5128f72017-09-20 07:24:15 +0000177 clangd::Logger &Logger,
Ilya Biryukova46f7a92017-06-28 10:34:50 +0000178 llvm::Optional<StringRef> ResourceDir)
Ilya Biryukove5128f72017-09-20 07:24:15 +0000179 : Logger(Logger), CDB(CDB), DiagConsumer(DiagConsumer),
180 FSProvider(FSProvider),
Ilya Biryukova46f7a92017-06-28 10:34:50 +0000181 ResourceDir(ResourceDir ? ResourceDir->str() : getStandardResourceDir()),
Ilya Biryukov38d79772017-05-16 09:38:59 +0000182 PCHs(std::make_shared<PCHContainerOperations>()),
Ilya Biryukovb080cb12017-10-23 14:46:48 +0000183 CodeCompleteOpts(CodeCompleteOpts), WorkScheduler(AsyncThreadsCount) {}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000184
Marc-Andre Laperle37de9712017-09-27 15:31:17 +0000185void ClangdServer::setRootPath(PathRef RootPath) {
186 std::string NewRootPath = llvm::sys::path::convert_to_slash(
187 RootPath, llvm::sys::path::Style::posix);
188 if (llvm::sys::fs::is_directory(NewRootPath))
189 this->RootPath = NewRootPath;
190}
191
Ilya Biryukov02d58702017-08-01 15:51:38 +0000192std::future<void> ClangdServer::addDocument(PathRef File, StringRef Contents) {
Ilya Biryukovf01af682017-05-23 13:42:59 +0000193 DocVersion Version = DraftMgr.updateDraft(File, Contents);
Ilya Biryukovf01af682017-05-23 13:42:59 +0000194
Ilya Biryukov02d58702017-08-01 15:51:38 +0000195 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
Benjamin Kramer5349eed2017-10-28 17:32:56 +0000196 std::shared_ptr<CppFile> Resources =
197 Units.getOrCreateFile(File, ResourceDir, CDB, PCHs, Logger);
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000198 return scheduleReparseAndDiags(File, VersionedDraft{Version, Contents.str()},
199 std::move(Resources), std::move(TaggedFS));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000200}
201
Ilya Biryukov02d58702017-08-01 15:51:38 +0000202std::future<void> ClangdServer::removeDocument(PathRef File) {
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000203 DraftMgr.removeDraft(File);
204 std::shared_ptr<CppFile> Resources = Units.removeIfPresent(File);
205 return scheduleCancelRebuild(std::move(Resources));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000206}
207
Ilya Biryukov02d58702017-08-01 15:51:38 +0000208std::future<void> ClangdServer::forceReparse(PathRef File) {
Ilya Biryukov91dbf5b2017-08-14 08:37:32 +0000209 auto FileContents = DraftMgr.getDraft(File);
210 assert(FileContents.Draft &&
211 "forceReparse() was called for non-added document");
212
213 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
Benjamin Kramer5349eed2017-10-28 17:32:56 +0000214 auto Recreated = Units.recreateFileIfCompileCommandChanged(File, ResourceDir,
215 CDB, PCHs, Logger);
Ilya Biryukov91dbf5b2017-08-14 08:37:32 +0000216
217 // Note that std::future from this cleanup action is ignored.
218 scheduleCancelRebuild(std::move(Recreated.RemovedFile));
219 // Schedule a reparse.
220 return scheduleReparseAndDiags(File, std::move(FileContents),
221 std::move(Recreated.FileInCollection),
222 std::move(TaggedFS));
Ilya Biryukov0f62ed22017-05-26 12:26:51 +0000223}
224
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000225std::future<Tagged<std::vector<CompletionItem>>>
Ilya Biryukov0e27ce42017-06-13 14:15:56 +0000226ClangdServer::codeComplete(PathRef File, Position Pos,
Ilya Biryukoved99e4c2017-07-31 17:09:29 +0000227 llvm::Optional<StringRef> OverridenContents,
228 IntrusiveRefCntPtr<vfs::FileSystem> *UsedFS) {
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000229 using ResultType = Tagged<std::vector<CompletionItem>>;
230
231 std::promise<ResultType> ResultPromise;
232
233 auto Callback = [](std::promise<ResultType> ResultPromise,
234 ResultType Result) -> void {
235 ResultPromise.set_value(std::move(Result));
236 };
237
238 std::future<ResultType> ResultFuture = ResultPromise.get_future();
239 codeComplete(BindWithForward(Callback, std::move(ResultPromise)), File, Pos,
240 OverridenContents, UsedFS);
241 return ResultFuture;
242}
243
244void ClangdServer::codeComplete(
245 UniqueFunction<void(Tagged<std::vector<CompletionItem>>)> Callback,
246 PathRef File, Position Pos, llvm::Optional<StringRef> OverridenContents,
247 IntrusiveRefCntPtr<vfs::FileSystem> *UsedFS) {
248 using CallbackType =
249 UniqueFunction<void(Tagged<std::vector<CompletionItem>>)>;
250
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000251 std::string Contents;
252 if (OverridenContents) {
253 Contents = *OverridenContents;
254 } else {
Ilya Biryukov0e27ce42017-06-13 14:15:56 +0000255 auto FileContents = DraftMgr.getDraft(File);
256 assert(FileContents.Draft &&
257 "codeComplete is called for non-added document");
258
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000259 Contents = std::move(*FileContents.Draft);
Ilya Biryukov0e27ce42017-06-13 14:15:56 +0000260 }
Ilya Biryukov38d79772017-05-16 09:38:59 +0000261
Ilya Biryukovaf0c04b2017-06-14 09:46:44 +0000262 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
Ilya Biryukoved99e4c2017-07-31 17:09:29 +0000263 if (UsedFS)
264 *UsedFS = TaggedFS.Value;
265
Ilya Biryukov02d58702017-08-01 15:51:38 +0000266 std::shared_ptr<CppFile> Resources = Units.getFile(File);
267 assert(Resources && "Calling completion on non-added file");
268
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000269 // Remember the current Preamble and use it when async task starts executing.
270 // At the point when async task starts executing, we may have a different
271 // Preamble in Resources. However, we assume the Preamble that we obtain here
272 // is reusable in completion more often.
273 std::shared_ptr<const PreambleData> Preamble =
274 Resources->getPossiblyStalePreamble();
275 // A task that will be run asynchronously.
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000276 auto Task =
277 // 'mutable' to reassign Preamble variable.
278 [=](CallbackType Callback) mutable {
279 if (!Preamble) {
280 // Maybe we built some preamble before processing this request.
281 Preamble = Resources->getPossiblyStalePreamble();
282 }
283 // FIXME(ibiryukov): even if Preamble is non-null, we may want to check
284 // both the old and the new version in case only one of them matches.
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000285
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000286 std::vector<CompletionItem> Result = clangd::codeComplete(
287 File, Resources->getCompileCommand(),
288 Preamble ? &Preamble->Preamble : nullptr, Contents, Pos,
289 TaggedFS.Value, PCHs, CodeCompleteOpts, Logger);
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000290
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000291 Callback(make_tagged(std::move(Result), std::move(TaggedFS.Tag)));
292 };
293
294 WorkScheduler.addToFront(std::move(Task), std::move(Callback));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000295}
Ilya Biryukovf01af682017-05-23 13:42:59 +0000296
Benjamin Krameree19f162017-10-26 12:28:13 +0000297llvm::Expected<Tagged<SignatureHelp>>
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000298ClangdServer::signatureHelp(PathRef File, Position Pos,
299 llvm::Optional<StringRef> OverridenContents,
300 IntrusiveRefCntPtr<vfs::FileSystem> *UsedFS) {
301 std::string DraftStorage;
302 if (!OverridenContents) {
303 auto FileContents = DraftMgr.getDraft(File);
Benjamin Krameree19f162017-10-26 12:28:13 +0000304 if (!FileContents.Draft)
305 return llvm::make_error<llvm::StringError>(
306 "signatureHelp is called for non-added document",
307 llvm::errc::invalid_argument);
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000308
309 DraftStorage = std::move(*FileContents.Draft);
310 OverridenContents = DraftStorage;
311 }
312
313 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
314 if (UsedFS)
315 *UsedFS = TaggedFS.Value;
316
317 std::shared_ptr<CppFile> Resources = Units.getFile(File);
Benjamin Krameree19f162017-10-26 12:28:13 +0000318 if (!Resources)
319 return llvm::make_error<llvm::StringError>(
320 "signatureHelp is called for non-added document",
321 llvm::errc::invalid_argument);
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000322
323 auto Preamble = Resources->getPossiblyStalePreamble();
324 auto Result = clangd::signatureHelp(File, Resources->getCompileCommand(),
325 Preamble ? &Preamble->Preamble : nullptr,
326 *OverridenContents, Pos, TaggedFS.Value,
327 PCHs, Logger);
328 return make_tagged(std::move(Result), TaggedFS.Tag);
329}
330
Ilya Biryukovafb55542017-05-16 14:40:30 +0000331std::vector<tooling::Replacement> ClangdServer::formatRange(PathRef File,
332 Range Rng) {
333 std::string Code = getDocument(File);
334
335 size_t Begin = positionToOffset(Code, Rng.start);
336 size_t Len = positionToOffset(Code, Rng.end) - Begin;
337 return formatCode(Code, File, {tooling::Range(Begin, Len)});
338}
339
340std::vector<tooling::Replacement> ClangdServer::formatFile(PathRef File) {
341 // Format everything.
342 std::string Code = getDocument(File);
343 return formatCode(Code, File, {tooling::Range(0, Code.size())});
344}
345
346std::vector<tooling::Replacement> ClangdServer::formatOnType(PathRef File,
347 Position Pos) {
348 // Look for the previous opening brace from the character position and
349 // format starting from there.
350 std::string Code = getDocument(File);
351 size_t CursorPos = positionToOffset(Code, Pos);
352 size_t PreviousLBracePos = StringRef(Code).find_last_of('{', CursorPos);
353 if (PreviousLBracePos == StringRef::npos)
354 PreviousLBracePos = CursorPos;
355 size_t Len = 1 + CursorPos - PreviousLBracePos;
356
357 return formatCode(Code, File, {tooling::Range(PreviousLBracePos, Len)});
358}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000359
Haojian Wu345099c2017-11-09 11:30:04 +0000360Expected<std::vector<tooling::Replacement>>
361ClangdServer::rename(PathRef File, Position Pos, llvm::StringRef NewName) {
362 std::string Code = getDocument(File);
363 std::shared_ptr<CppFile> Resources = Units.getFile(File);
364 RefactoringResultCollector ResultCollector;
365 Resources->getAST().get()->runUnderLock([&](ParsedAST *AST) {
366 const SourceManager &SourceMgr = AST->getASTContext().getSourceManager();
367 const FileEntry *FE =
368 SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
369 if (!FE)
370 return;
371 SourceLocation SourceLocationBeg =
372 clangd::getBeginningOfIdentifier(*AST, Pos, FE);
373 tooling::RefactoringRuleContext Context(
374 AST->getASTContext().getSourceManager());
375 Context.setASTContext(AST->getASTContext());
376 auto Rename = clang::tooling::RenameOccurrences::initiate(
377 Context, SourceRange(SourceLocationBeg), NewName.str());
378 if (!Rename) {
379 ResultCollector.Result = Rename.takeError();
380 return;
381 }
382 Rename->invoke(ResultCollector, Context);
383 });
384 assert(ResultCollector.Result.hasValue());
385 if (!ResultCollector.Result.getValue())
386 return ResultCollector.Result->takeError();
387
388 std::vector<tooling::Replacement> Replacements;
389 for (const tooling::AtomicChange &Change : ResultCollector.Result->get()) {
390 tooling::Replacements ChangeReps = Change.getReplacements();
391 for (const auto &Rep : ChangeReps) {
392 // FIXME: Right now we only support renaming the main file, so we drop
393 // replacements not for the main file. In the future, we might consider to
394 // support:
395 // * rename in any included header
396 // * rename only in the "main" header
397 // * provide an error if there are symbols we won't rename (e.g.
398 // std::vector)
399 // * rename globally in project
400 // * rename in open files
401 if (Rep.getFilePath() == File)
402 Replacements.push_back(Rep);
403 }
404 }
405 return Replacements;
406}
407
Ilya Biryukov38d79772017-05-16 09:38:59 +0000408std::string ClangdServer::getDocument(PathRef File) {
409 auto draft = DraftMgr.getDraft(File);
410 assert(draft.Draft && "File is not tracked, cannot get contents");
411 return *draft.Draft;
412}
413
Ilya Biryukovf01af682017-05-23 13:42:59 +0000414std::string ClangdServer::dumpAST(PathRef File) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000415 std::shared_ptr<CppFile> Resources = Units.getFile(File);
416 assert(Resources && "dumpAST is called for non-added document");
Ilya Biryukov38d79772017-05-16 09:38:59 +0000417
Ilya Biryukov02d58702017-08-01 15:51:38 +0000418 std::string Result;
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +0000419 Resources->getAST().get()->runUnderLock([&Result](ParsedAST *AST) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000420 llvm::raw_string_ostream ResultOS(Result);
421 if (AST) {
422 clangd::dumpAST(*AST, ResultOS);
423 } else {
424 ResultOS << "<no-ast>";
425 }
426 ResultOS.flush();
Ilya Biryukovf01af682017-05-23 13:42:59 +0000427 });
Ilya Biryukov02d58702017-08-01 15:51:38 +0000428 return Result;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000429}
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000430
Benjamin Krameree19f162017-10-26 12:28:13 +0000431llvm::Expected<Tagged<std::vector<Location>>>
432ClangdServer::findDefinitions(PathRef File, Position Pos) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000433 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
434
435 std::shared_ptr<CppFile> Resources = Units.getFile(File);
Benjamin Krameree19f162017-10-26 12:28:13 +0000436 if (!Resources)
437 return llvm::make_error<llvm::StringError>(
438 "findDefinitions called on non-added file",
439 llvm::errc::invalid_argument);
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000440
441 std::vector<Location> Result;
Ilya Biryukove5128f72017-09-20 07:24:15 +0000442 Resources->getAST().get()->runUnderLock([Pos, &Result, this](ParsedAST *AST) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000443 if (!AST)
444 return;
Ilya Biryukove5128f72017-09-20 07:24:15 +0000445 Result = clangd::findDefinitions(*AST, Pos, Logger);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000446 });
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000447 return make_tagged(std::move(Result), TaggedFS.Tag);
448}
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000449
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000450llvm::Optional<Path> ClangdServer::switchSourceHeader(PathRef Path) {
451
452 StringRef SourceExtensions[] = {".cpp", ".c", ".cc", ".cxx",
453 ".c++", ".m", ".mm"};
454 StringRef HeaderExtensions[] = {".h", ".hh", ".hpp", ".hxx", ".inc"};
455
456 StringRef PathExt = llvm::sys::path::extension(Path);
457
458 // Lookup in a list of known extensions.
459 auto SourceIter =
460 std::find_if(std::begin(SourceExtensions), std::end(SourceExtensions),
461 [&PathExt](PathRef SourceExt) {
462 return SourceExt.equals_lower(PathExt);
463 });
464 bool IsSource = SourceIter != std::end(SourceExtensions);
465
466 auto HeaderIter =
467 std::find_if(std::begin(HeaderExtensions), std::end(HeaderExtensions),
468 [&PathExt](PathRef HeaderExt) {
469 return HeaderExt.equals_lower(PathExt);
470 });
471
472 bool IsHeader = HeaderIter != std::end(HeaderExtensions);
473
474 // We can only switch between extensions known extensions.
475 if (!IsSource && !IsHeader)
476 return llvm::None;
477
478 // Array to lookup extensions for the switch. An opposite of where original
479 // extension was found.
480 ArrayRef<StringRef> NewExts;
481 if (IsSource)
482 NewExts = HeaderExtensions;
483 else
484 NewExts = SourceExtensions;
485
486 // Storage for the new path.
487 SmallString<128> NewPath = StringRef(Path);
488
489 // Instance of vfs::FileSystem, used for file existence checks.
490 auto FS = FSProvider.getTaggedFileSystem(Path).Value;
491
492 // Loop through switched extension candidates.
493 for (StringRef NewExt : NewExts) {
494 llvm::sys::path::replace_extension(NewPath, NewExt);
495 if (FS->exists(NewPath))
496 return NewPath.str().str(); // First str() to convert from SmallString to
497 // StringRef, second to convert from StringRef
498 // to std::string
Ilya Biryukov33334942017-10-06 14:39:39 +0000499
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000500 // Also check NewExt in upper-case, just in case.
501 llvm::sys::path::replace_extension(NewPath, NewExt.upper());
502 if (FS->exists(NewPath))
503 return NewPath.str().str();
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000504 }
505
506 return llvm::None;
507}
508
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000509std::future<void> ClangdServer::scheduleReparseAndDiags(
510 PathRef File, VersionedDraft Contents, std::shared_ptr<CppFile> Resources,
511 Tagged<IntrusiveRefCntPtr<vfs::FileSystem>> TaggedFS) {
512
513 assert(Contents.Draft && "Draft must have contents");
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000514 UniqueFunction<llvm::Optional<std::vector<DiagWithFixIts>>()>
515 DeferredRebuild =
516 Resources->deferRebuild(*Contents.Draft, TaggedFS.Value);
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000517 std::promise<void> DonePromise;
518 std::future<void> DoneFuture = DonePromise.get_future();
519
520 DocVersion Version = Contents.Version;
521 Path FileStr = File;
522 VFSTag Tag = TaggedFS.Tag;
523 auto ReparseAndPublishDiags =
524 [this, FileStr, Version,
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000525 Tag](UniqueFunction<llvm::Optional<std::vector<DiagWithFixIts>>()>
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000526 DeferredRebuild,
527 std::promise<void> DonePromise) -> void {
528 FulfillPromiseGuard Guard(DonePromise);
529
530 auto CurrentVersion = DraftMgr.getVersion(FileStr);
531 if (CurrentVersion != Version)
532 return; // This request is outdated
533
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000534 auto Diags = DeferredRebuild();
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000535 if (!Diags)
536 return; // A new reparse was requested before this one completed.
Ilya Biryukov47f22022017-09-20 12:58:55 +0000537
538 // We need to serialize access to resulting diagnostics to avoid calling
539 // `onDiagnosticsReady` in the wrong order.
540 std::lock_guard<std::mutex> DiagsLock(DiagnosticsMutex);
541 DocVersion &LastReportedDiagsVersion = ReportedDiagnosticVersions[FileStr];
542 // FIXME(ibiryukov): get rid of '<' comparison here. In the current
543 // implementation diagnostics will not be reported after version counters'
544 // overflow. This should not happen in practice, since DocVersion is a
545 // 64-bit unsigned integer.
546 if (Version < LastReportedDiagsVersion)
547 return;
548 LastReportedDiagsVersion = Version;
549
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000550 DiagConsumer.onDiagnosticsReady(FileStr,
551 make_tagged(std::move(*Diags), Tag));
552 };
553
554 WorkScheduler.addToFront(std::move(ReparseAndPublishDiags),
555 std::move(DeferredRebuild), std::move(DonePromise));
556 return DoneFuture;
557}
558
559std::future<void>
560ClangdServer::scheduleCancelRebuild(std::shared_ptr<CppFile> Resources) {
561 std::promise<void> DonePromise;
562 std::future<void> DoneFuture = DonePromise.get_future();
563 if (!Resources) {
564 // No need to schedule any cleanup.
565 DonePromise.set_value();
566 return DoneFuture;
567 }
568
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000569 UniqueFunction<void()> DeferredCancel = Resources->deferCancelRebuild();
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000570 auto CancelReparses = [Resources](std::promise<void> DonePromise,
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000571 UniqueFunction<void()> DeferredCancel) {
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000572 FulfillPromiseGuard Guard(DonePromise);
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000573 DeferredCancel();
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000574 };
575 WorkScheduler.addToFront(std::move(CancelReparses), std::move(DonePromise),
576 std::move(DeferredCancel));
577 return DoneFuture;
578}
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000579
580void ClangdServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
581 // FIXME: Do nothing for now. This will be used for indexing and potentially
582 // invalidating other caches.
583}