blob: 3dece2491d6cb60b511703629d58f09f55b7af12 [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
Sam McCalla40371b2017-11-15 09:16:29 +0000225std::future<Tagged<CompletionList>>
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) {
Sam McCalla40371b2017-11-15 09:16:29 +0000229 using ResultType = Tagged<CompletionList>;
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000230
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(
Sam McCalla40371b2017-11-15 09:16:29 +0000245 UniqueFunction<void(Tagged<CompletionList>)> Callback, PathRef File,
246 Position Pos, llvm::Optional<StringRef> OverridenContents,
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000247 IntrusiveRefCntPtr<vfs::FileSystem> *UsedFS) {
Sam McCalla40371b2017-11-15 09:16:29 +0000248 using CallbackType = UniqueFunction<void(Tagged<CompletionList>)>;
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000249
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000250 std::string Contents;
251 if (OverridenContents) {
252 Contents = *OverridenContents;
253 } else {
Ilya Biryukov0e27ce42017-06-13 14:15:56 +0000254 auto FileContents = DraftMgr.getDraft(File);
255 assert(FileContents.Draft &&
256 "codeComplete is called for non-added document");
257
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000258 Contents = std::move(*FileContents.Draft);
Ilya Biryukov0e27ce42017-06-13 14:15:56 +0000259 }
Ilya Biryukov38d79772017-05-16 09:38:59 +0000260
Ilya Biryukovaf0c04b2017-06-14 09:46:44 +0000261 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
Ilya Biryukoved99e4c2017-07-31 17:09:29 +0000262 if (UsedFS)
263 *UsedFS = TaggedFS.Value;
264
Ilya Biryukov02d58702017-08-01 15:51:38 +0000265 std::shared_ptr<CppFile> Resources = Units.getFile(File);
266 assert(Resources && "Calling completion on non-added file");
267
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000268 // Remember the current Preamble and use it when async task starts executing.
269 // At the point when async task starts executing, we may have a different
270 // Preamble in Resources. However, we assume the Preamble that we obtain here
271 // is reusable in completion more often.
272 std::shared_ptr<const PreambleData> Preamble =
273 Resources->getPossiblyStalePreamble();
274 // A task that will be run asynchronously.
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000275 auto Task =
276 // 'mutable' to reassign Preamble variable.
277 [=](CallbackType Callback) mutable {
278 if (!Preamble) {
279 // Maybe we built some preamble before processing this request.
280 Preamble = Resources->getPossiblyStalePreamble();
281 }
282 // FIXME(ibiryukov): even if Preamble is non-null, we may want to check
283 // both the old and the new version in case only one of them matches.
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000284
Sam McCalla40371b2017-11-15 09:16:29 +0000285 CompletionList Result = clangd::codeComplete(
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000286 File, Resources->getCompileCommand(),
287 Preamble ? &Preamble->Preamble : nullptr, Contents, Pos,
288 TaggedFS.Value, PCHs, CodeCompleteOpts, Logger);
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000289
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000290 Callback(make_tagged(std::move(Result), std::move(TaggedFS.Tag)));
291 };
292
293 WorkScheduler.addToFront(std::move(Task), std::move(Callback));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000294}
Ilya Biryukovf01af682017-05-23 13:42:59 +0000295
Benjamin Krameree19f162017-10-26 12:28:13 +0000296llvm::Expected<Tagged<SignatureHelp>>
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000297ClangdServer::signatureHelp(PathRef File, Position Pos,
298 llvm::Optional<StringRef> OverridenContents,
299 IntrusiveRefCntPtr<vfs::FileSystem> *UsedFS) {
300 std::string DraftStorage;
301 if (!OverridenContents) {
302 auto FileContents = DraftMgr.getDraft(File);
Benjamin Krameree19f162017-10-26 12:28:13 +0000303 if (!FileContents.Draft)
304 return llvm::make_error<llvm::StringError>(
305 "signatureHelp is called for non-added document",
306 llvm::errc::invalid_argument);
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000307
308 DraftStorage = std::move(*FileContents.Draft);
309 OverridenContents = DraftStorage;
310 }
311
312 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
313 if (UsedFS)
314 *UsedFS = TaggedFS.Value;
315
316 std::shared_ptr<CppFile> Resources = Units.getFile(File);
Benjamin Krameree19f162017-10-26 12:28:13 +0000317 if (!Resources)
318 return llvm::make_error<llvm::StringError>(
319 "signatureHelp is called for non-added document",
320 llvm::errc::invalid_argument);
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000321
322 auto Preamble = Resources->getPossiblyStalePreamble();
323 auto Result = clangd::signatureHelp(File, Resources->getCompileCommand(),
324 Preamble ? &Preamble->Preamble : nullptr,
325 *OverridenContents, Pos, TaggedFS.Value,
326 PCHs, Logger);
327 return make_tagged(std::move(Result), TaggedFS.Tag);
328}
329
Ilya Biryukovafb55542017-05-16 14:40:30 +0000330std::vector<tooling::Replacement> ClangdServer::formatRange(PathRef File,
331 Range Rng) {
332 std::string Code = getDocument(File);
333
334 size_t Begin = positionToOffset(Code, Rng.start);
335 size_t Len = positionToOffset(Code, Rng.end) - Begin;
336 return formatCode(Code, File, {tooling::Range(Begin, Len)});
337}
338
339std::vector<tooling::Replacement> ClangdServer::formatFile(PathRef File) {
340 // Format everything.
341 std::string Code = getDocument(File);
342 return formatCode(Code, File, {tooling::Range(0, Code.size())});
343}
344
345std::vector<tooling::Replacement> ClangdServer::formatOnType(PathRef File,
346 Position Pos) {
347 // Look for the previous opening brace from the character position and
348 // format starting from there.
349 std::string Code = getDocument(File);
350 size_t CursorPos = positionToOffset(Code, Pos);
351 size_t PreviousLBracePos = StringRef(Code).find_last_of('{', CursorPos);
352 if (PreviousLBracePos == StringRef::npos)
353 PreviousLBracePos = CursorPos;
354 size_t Len = 1 + CursorPos - PreviousLBracePos;
355
356 return formatCode(Code, File, {tooling::Range(PreviousLBracePos, Len)});
357}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000358
Haojian Wu345099c2017-11-09 11:30:04 +0000359Expected<std::vector<tooling::Replacement>>
360ClangdServer::rename(PathRef File, Position Pos, llvm::StringRef NewName) {
361 std::string Code = getDocument(File);
362 std::shared_ptr<CppFile> Resources = Units.getFile(File);
363 RefactoringResultCollector ResultCollector;
364 Resources->getAST().get()->runUnderLock([&](ParsedAST *AST) {
365 const SourceManager &SourceMgr = AST->getASTContext().getSourceManager();
366 const FileEntry *FE =
367 SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
368 if (!FE)
369 return;
370 SourceLocation SourceLocationBeg =
371 clangd::getBeginningOfIdentifier(*AST, Pos, FE);
372 tooling::RefactoringRuleContext Context(
373 AST->getASTContext().getSourceManager());
374 Context.setASTContext(AST->getASTContext());
375 auto Rename = clang::tooling::RenameOccurrences::initiate(
376 Context, SourceRange(SourceLocationBeg), NewName.str());
377 if (!Rename) {
378 ResultCollector.Result = Rename.takeError();
379 return;
380 }
381 Rename->invoke(ResultCollector, Context);
382 });
383 assert(ResultCollector.Result.hasValue());
384 if (!ResultCollector.Result.getValue())
385 return ResultCollector.Result->takeError();
386
387 std::vector<tooling::Replacement> Replacements;
388 for (const tooling::AtomicChange &Change : ResultCollector.Result->get()) {
389 tooling::Replacements ChangeReps = Change.getReplacements();
390 for (const auto &Rep : ChangeReps) {
391 // FIXME: Right now we only support renaming the main file, so we drop
392 // replacements not for the main file. In the future, we might consider to
393 // support:
394 // * rename in any included header
395 // * rename only in the "main" header
396 // * provide an error if there are symbols we won't rename (e.g.
397 // std::vector)
398 // * rename globally in project
399 // * rename in open files
400 if (Rep.getFilePath() == File)
401 Replacements.push_back(Rep);
402 }
403 }
404 return Replacements;
405}
406
Ilya Biryukov38d79772017-05-16 09:38:59 +0000407std::string ClangdServer::getDocument(PathRef File) {
408 auto draft = DraftMgr.getDraft(File);
409 assert(draft.Draft && "File is not tracked, cannot get contents");
410 return *draft.Draft;
411}
412
Ilya Biryukovf01af682017-05-23 13:42:59 +0000413std::string ClangdServer::dumpAST(PathRef File) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000414 std::shared_ptr<CppFile> Resources = Units.getFile(File);
415 assert(Resources && "dumpAST is called for non-added document");
Ilya Biryukov38d79772017-05-16 09:38:59 +0000416
Ilya Biryukov02d58702017-08-01 15:51:38 +0000417 std::string Result;
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +0000418 Resources->getAST().get()->runUnderLock([&Result](ParsedAST *AST) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000419 llvm::raw_string_ostream ResultOS(Result);
420 if (AST) {
421 clangd::dumpAST(*AST, ResultOS);
422 } else {
423 ResultOS << "<no-ast>";
424 }
425 ResultOS.flush();
Ilya Biryukovf01af682017-05-23 13:42:59 +0000426 });
Ilya Biryukov02d58702017-08-01 15:51:38 +0000427 return Result;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000428}
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000429
Benjamin Krameree19f162017-10-26 12:28:13 +0000430llvm::Expected<Tagged<std::vector<Location>>>
431ClangdServer::findDefinitions(PathRef File, Position Pos) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000432 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
433
434 std::shared_ptr<CppFile> Resources = Units.getFile(File);
Benjamin Krameree19f162017-10-26 12:28:13 +0000435 if (!Resources)
436 return llvm::make_error<llvm::StringError>(
437 "findDefinitions called on non-added file",
438 llvm::errc::invalid_argument);
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000439
440 std::vector<Location> Result;
Ilya Biryukove5128f72017-09-20 07:24:15 +0000441 Resources->getAST().get()->runUnderLock([Pos, &Result, this](ParsedAST *AST) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000442 if (!AST)
443 return;
Ilya Biryukove5128f72017-09-20 07:24:15 +0000444 Result = clangd::findDefinitions(*AST, Pos, Logger);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000445 });
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000446 return make_tagged(std::move(Result), TaggedFS.Tag);
447}
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000448
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000449llvm::Optional<Path> ClangdServer::switchSourceHeader(PathRef Path) {
450
451 StringRef SourceExtensions[] = {".cpp", ".c", ".cc", ".cxx",
452 ".c++", ".m", ".mm"};
453 StringRef HeaderExtensions[] = {".h", ".hh", ".hpp", ".hxx", ".inc"};
454
455 StringRef PathExt = llvm::sys::path::extension(Path);
456
457 // Lookup in a list of known extensions.
458 auto SourceIter =
459 std::find_if(std::begin(SourceExtensions), std::end(SourceExtensions),
460 [&PathExt](PathRef SourceExt) {
461 return SourceExt.equals_lower(PathExt);
462 });
463 bool IsSource = SourceIter != std::end(SourceExtensions);
464
465 auto HeaderIter =
466 std::find_if(std::begin(HeaderExtensions), std::end(HeaderExtensions),
467 [&PathExt](PathRef HeaderExt) {
468 return HeaderExt.equals_lower(PathExt);
469 });
470
471 bool IsHeader = HeaderIter != std::end(HeaderExtensions);
472
473 // We can only switch between extensions known extensions.
474 if (!IsSource && !IsHeader)
475 return llvm::None;
476
477 // Array to lookup extensions for the switch. An opposite of where original
478 // extension was found.
479 ArrayRef<StringRef> NewExts;
480 if (IsSource)
481 NewExts = HeaderExtensions;
482 else
483 NewExts = SourceExtensions;
484
485 // Storage for the new path.
486 SmallString<128> NewPath = StringRef(Path);
487
488 // Instance of vfs::FileSystem, used for file existence checks.
489 auto FS = FSProvider.getTaggedFileSystem(Path).Value;
490
491 // Loop through switched extension candidates.
492 for (StringRef NewExt : NewExts) {
493 llvm::sys::path::replace_extension(NewPath, NewExt);
494 if (FS->exists(NewPath))
495 return NewPath.str().str(); // First str() to convert from SmallString to
496 // StringRef, second to convert from StringRef
497 // to std::string
Ilya Biryukov33334942017-10-06 14:39:39 +0000498
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000499 // Also check NewExt in upper-case, just in case.
500 llvm::sys::path::replace_extension(NewPath, NewExt.upper());
501 if (FS->exists(NewPath))
502 return NewPath.str().str();
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000503 }
504
505 return llvm::None;
506}
507
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000508std::future<void> ClangdServer::scheduleReparseAndDiags(
509 PathRef File, VersionedDraft Contents, std::shared_ptr<CppFile> Resources,
510 Tagged<IntrusiveRefCntPtr<vfs::FileSystem>> TaggedFS) {
511
512 assert(Contents.Draft && "Draft must have contents");
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000513 UniqueFunction<llvm::Optional<std::vector<DiagWithFixIts>>()>
514 DeferredRebuild =
515 Resources->deferRebuild(*Contents.Draft, TaggedFS.Value);
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000516 std::promise<void> DonePromise;
517 std::future<void> DoneFuture = DonePromise.get_future();
518
519 DocVersion Version = Contents.Version;
520 Path FileStr = File;
521 VFSTag Tag = TaggedFS.Tag;
522 auto ReparseAndPublishDiags =
523 [this, FileStr, Version,
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000524 Tag](UniqueFunction<llvm::Optional<std::vector<DiagWithFixIts>>()>
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000525 DeferredRebuild,
526 std::promise<void> DonePromise) -> void {
527 FulfillPromiseGuard Guard(DonePromise);
528
529 auto CurrentVersion = DraftMgr.getVersion(FileStr);
530 if (CurrentVersion != Version)
531 return; // This request is outdated
532
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000533 auto Diags = DeferredRebuild();
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000534 if (!Diags)
535 return; // A new reparse was requested before this one completed.
Ilya Biryukov47f22022017-09-20 12:58:55 +0000536
537 // We need to serialize access to resulting diagnostics to avoid calling
538 // `onDiagnosticsReady` in the wrong order.
539 std::lock_guard<std::mutex> DiagsLock(DiagnosticsMutex);
540 DocVersion &LastReportedDiagsVersion = ReportedDiagnosticVersions[FileStr];
541 // FIXME(ibiryukov): get rid of '<' comparison here. In the current
542 // implementation diagnostics will not be reported after version counters'
543 // overflow. This should not happen in practice, since DocVersion is a
544 // 64-bit unsigned integer.
545 if (Version < LastReportedDiagsVersion)
546 return;
547 LastReportedDiagsVersion = Version;
548
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000549 DiagConsumer.onDiagnosticsReady(FileStr,
550 make_tagged(std::move(*Diags), Tag));
551 };
552
553 WorkScheduler.addToFront(std::move(ReparseAndPublishDiags),
554 std::move(DeferredRebuild), std::move(DonePromise));
555 return DoneFuture;
556}
557
558std::future<void>
559ClangdServer::scheduleCancelRebuild(std::shared_ptr<CppFile> Resources) {
560 std::promise<void> DonePromise;
561 std::future<void> DoneFuture = DonePromise.get_future();
562 if (!Resources) {
563 // No need to schedule any cleanup.
564 DonePromise.set_value();
565 return DoneFuture;
566 }
567
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000568 UniqueFunction<void()> DeferredCancel = Resources->deferCancelRebuild();
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000569 auto CancelReparses = [Resources](std::promise<void> DonePromise,
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000570 UniqueFunction<void()> DeferredCancel) {
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000571 FulfillPromiseGuard Guard(DonePromise);
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000572 DeferredCancel();
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000573 };
574 WorkScheduler.addToFront(std::move(CancelReparses), std::move(DonePromise),
575 std::move(DeferredCancel));
576 return DoneFuture;
577}
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000578
579void ClangdServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
580 // FIXME: Do nothing for now. This will be used for indexing and potentially
581 // invalidating other caches.
582}