blob: 7e48d682e400a611629cfcc638c0fb7fe405aae7 [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 Biryukova46f7a92017-06-28 10:34:50 +000031std::string getStandardResourceDir() {
32 static int Dummy; // Just an address in this process.
33 return CompilerInvocation::GetResourcesPath("clangd", (void *)&Dummy);
34}
35
Haojian Wu345099c2017-11-09 11:30:04 +000036class RefactoringResultCollector final
37 : public tooling::RefactoringResultConsumer {
38public:
39 void handleError(llvm::Error Err) override {
40 assert(!Result.hasValue());
41 // FIXME: figure out a way to return better message for DiagnosticError.
42 // clangd uses llvm::toString to convert the Err to string, however, for
43 // DiagnosticError, only "clang diagnostic" will be generated.
44 Result = std::move(Err);
45 }
46
47 // Using the handle(SymbolOccurrences) from parent class.
48 using tooling::RefactoringResultConsumer::handle;
49
50 void handle(tooling::AtomicChanges SourceReplacements) override {
51 assert(!Result.hasValue());
52 Result = std::move(SourceReplacements);
53 }
54
55 Optional<Expected<tooling::AtomicChanges>> Result;
56};
57
Ilya Biryukovafb55542017-05-16 14:40:30 +000058} // namespace
59
60size_t clangd::positionToOffset(StringRef Code, Position P) {
61 size_t Offset = 0;
62 for (int I = 0; I != P.line; ++I) {
63 // FIXME: \r\n
64 // FIXME: UTF-8
65 size_t F = Code.find('\n', Offset);
66 if (F == StringRef::npos)
67 return 0; // FIXME: Is this reasonable?
68 Offset = F + 1;
69 }
70 return (Offset == 0 ? 0 : (Offset - 1)) + P.character;
71}
72
73/// Turn an offset in Code into a [line, column] pair.
74Position clangd::offsetToPosition(StringRef Code, size_t Offset) {
75 StringRef JustBefore = Code.substr(0, Offset);
76 // FIXME: \r\n
77 // FIXME: UTF-8
78 int Lines = JustBefore.count('\n');
79 int Cols = JustBefore.size() - JustBefore.rfind('\n') - 1;
80 return {Lines, Cols};
81}
82
Ilya Biryukov22602992017-05-30 15:11:02 +000083Tagged<IntrusiveRefCntPtr<vfs::FileSystem>>
Ilya Biryukovaf0c04b2017-06-14 09:46:44 +000084RealFileSystemProvider::getTaggedFileSystem(PathRef File) {
Ilya Biryukov22602992017-05-30 15:11:02 +000085 return make_tagged(vfs::getRealFileSystem(), VFSTag());
Ilya Biryukov0f62ed22017-05-26 12:26:51 +000086}
87
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +000088unsigned clangd::getDefaultAsyncThreadsCount() {
89 unsigned HardwareConcurrency = std::thread::hardware_concurrency();
90 // C++ standard says that hardware_concurrency()
91 // may return 0, fallback to 1 worker thread in
92 // that case.
93 if (HardwareConcurrency == 0)
94 return 1;
95 return HardwareConcurrency;
96}
97
98ClangdScheduler::ClangdScheduler(unsigned AsyncThreadsCount)
99 : RunSynchronously(AsyncThreadsCount == 0) {
Ilya Biryukov38d79772017-05-16 09:38:59 +0000100 if (RunSynchronously) {
101 // Don't start the worker thread if we're running synchronously
102 return;
103 }
104
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000105 Workers.reserve(AsyncThreadsCount);
106 for (unsigned I = 0; I < AsyncThreadsCount; ++I) {
Sam McCall8567cb32017-11-02 09:21:51 +0000107 Workers.push_back(std::thread([this, I]() {
108 llvm::set_thread_name(llvm::formatv("scheduler/{0}", I));
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000109 while (true) {
Ilya Biryukov08e6ccb2017-10-09 16:26:26 +0000110 UniqueFunction<void()> Request;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000111
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000112 // Pick request from the queue
113 {
114 std::unique_lock<std::mutex> Lock(Mutex);
115 // Wait for more requests.
116 RequestCV.wait(Lock,
117 [this] { return !RequestQueue.empty() || Done; });
118 if (Done)
119 return;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000120
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000121 assert(!RequestQueue.empty() && "RequestQueue was empty");
Ilya Biryukov38d79772017-05-16 09:38:59 +0000122
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000123 // We process requests starting from the front of the queue. Users of
124 // ClangdScheduler have a way to prioritise their requests by putting
125 // them to the either side of the queue (using either addToEnd or
126 // addToFront).
127 Request = std::move(RequestQueue.front());
128 RequestQueue.pop_front();
129 } // unlock Mutex
Ilya Biryukov38d79772017-05-16 09:38:59 +0000130
Ilya Biryukov08e6ccb2017-10-09 16:26:26 +0000131 Request();
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000132 }
133 }));
134 }
Ilya Biryukov38d79772017-05-16 09:38:59 +0000135}
136
137ClangdScheduler::~ClangdScheduler() {
138 if (RunSynchronously)
139 return; // no worker thread is running in that case
140
141 {
142 std::lock_guard<std::mutex> Lock(Mutex);
143 // Wake up the worker thread
144 Done = true;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000145 } // unlock Mutex
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000146 RequestCV.notify_all();
147
148 for (auto &Worker : Workers)
149 Worker.join();
Ilya Biryukov38d79772017-05-16 09:38:59 +0000150}
151
Sam McCalladccab62017-11-23 16:58:22 +0000152ClangdServer::ClangdServer(GlobalCompilationDatabase &CDB,
153 DiagnosticsConsumer &DiagConsumer,
154 FileSystemProvider &FSProvider,
155 unsigned AsyncThreadsCount,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000156 bool StorePreamblesInMemory,
Sam McCalladccab62017-11-23 16:58:22 +0000157 llvm::Optional<StringRef> ResourceDir)
Ilya Biryukov940901e2017-12-13 12:51:22 +0000158 : CDB(CDB), DiagConsumer(DiagConsumer), FSProvider(FSProvider),
Ilya Biryukova46f7a92017-06-28 10:34:50 +0000159 ResourceDir(ResourceDir ? ResourceDir->str() : getStandardResourceDir()),
Ilya Biryukov38d79772017-05-16 09:38:59 +0000160 PCHs(std::make_shared<PCHContainerOperations>()),
Ilya Biryukove9eb7f02017-11-16 16:25:18 +0000161 StorePreamblesInMemory(StorePreamblesInMemory),
Ilya Biryukovd3b04e32017-12-05 10:42:57 +0000162 WorkScheduler(AsyncThreadsCount) {}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000163
Marc-Andre Laperle37de9712017-09-27 15:31:17 +0000164void ClangdServer::setRootPath(PathRef RootPath) {
165 std::string NewRootPath = llvm::sys::path::convert_to_slash(
166 RootPath, llvm::sys::path::Style::posix);
167 if (llvm::sys::fs::is_directory(NewRootPath))
168 this->RootPath = NewRootPath;
169}
170
Ilya Biryukov940901e2017-12-13 12:51:22 +0000171std::future<Context> ClangdServer::addDocument(Context Ctx, PathRef File,
172 StringRef Contents) {
Ilya Biryukovf01af682017-05-23 13:42:59 +0000173 DocVersion Version = DraftMgr.updateDraft(File, Contents);
Ilya Biryukovf01af682017-05-23 13:42:59 +0000174
Ilya Biryukov02d58702017-08-01 15:51:38 +0000175 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
Ilya Biryukove9eb7f02017-11-16 16:25:18 +0000176 std::shared_ptr<CppFile> Resources = Units.getOrCreateFile(
Ilya Biryukov940901e2017-12-13 12:51:22 +0000177 File, ResourceDir, CDB, StorePreamblesInMemory, PCHs);
178 return scheduleReparseAndDiags(std::move(Ctx), File,
179 VersionedDraft{Version, Contents.str()},
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000180 std::move(Resources), std::move(TaggedFS));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000181}
182
Ilya Biryukov940901e2017-12-13 12:51:22 +0000183std::future<Context> ClangdServer::removeDocument(Context Ctx, PathRef File) {
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000184 DraftMgr.removeDraft(File);
185 std::shared_ptr<CppFile> Resources = Units.removeIfPresent(File);
Ilya Biryukov940901e2017-12-13 12:51:22 +0000186 return scheduleCancelRebuild(std::move(Ctx), std::move(Resources));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000187}
188
Ilya Biryukov940901e2017-12-13 12:51:22 +0000189std::future<Context> ClangdServer::forceReparse(Context Ctx, PathRef File) {
Ilya Biryukov91dbf5b2017-08-14 08:37:32 +0000190 auto FileContents = DraftMgr.getDraft(File);
191 assert(FileContents.Draft &&
192 "forceReparse() was called for non-added document");
193
194 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
Ilya Biryukove9eb7f02017-11-16 16:25:18 +0000195 auto Recreated = Units.recreateFileIfCompileCommandChanged(
Ilya Biryukov940901e2017-12-13 12:51:22 +0000196 File, ResourceDir, CDB, StorePreamblesInMemory, PCHs);
Ilya Biryukov91dbf5b2017-08-14 08:37:32 +0000197
198 // Note that std::future from this cleanup action is ignored.
Ilya Biryukov940901e2017-12-13 12:51:22 +0000199 scheduleCancelRebuild(Ctx.clone(), std::move(Recreated.RemovedFile));
Ilya Biryukov91dbf5b2017-08-14 08:37:32 +0000200 // Schedule a reparse.
Ilya Biryukov940901e2017-12-13 12:51:22 +0000201 return scheduleReparseAndDiags(std::move(Ctx), File, std::move(FileContents),
Ilya Biryukov91dbf5b2017-08-14 08:37:32 +0000202 std::move(Recreated.FileInCollection),
203 std::move(TaggedFS));
Ilya Biryukov0f62ed22017-05-26 12:26:51 +0000204}
205
Ilya Biryukov940901e2017-12-13 12:51:22 +0000206std::future<std::pair<Context, Tagged<CompletionList>>>
207ClangdServer::codeComplete(Context Ctx, PathRef File, Position Pos,
Ilya Biryukovd3b04e32017-12-05 10:42:57 +0000208 const clangd::CodeCompleteOptions &Opts,
Ilya Biryukoved99e4c2017-07-31 17:09:29 +0000209 llvm::Optional<StringRef> OverridenContents,
210 IntrusiveRefCntPtr<vfs::FileSystem> *UsedFS) {
Ilya Biryukov940901e2017-12-13 12:51:22 +0000211 using ResultType = std::pair<Context, Tagged<CompletionList>>;
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000212
213 std::promise<ResultType> ResultPromise;
214
Ilya Biryukov940901e2017-12-13 12:51:22 +0000215 auto Callback = [](std::promise<ResultType> ResultPromise, Context Ctx,
216 Tagged<CompletionList> Result) -> void {
217 ResultPromise.set_value({std::move(Ctx), std::move(Result)});
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000218 };
219
220 std::future<ResultType> ResultFuture = ResultPromise.get_future();
Ilya Biryukov940901e2017-12-13 12:51:22 +0000221 codeComplete(std::move(Ctx), File, Pos, Opts,
222 BindWithForward(Callback, std::move(ResultPromise)),
223 OverridenContents, UsedFS);
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000224 return ResultFuture;
225}
226
227void ClangdServer::codeComplete(
Ilya Biryukov940901e2017-12-13 12:51:22 +0000228 Context Ctx, PathRef File, Position Pos,
229 const clangd::CodeCompleteOptions &Opts,
230 UniqueFunction<void(Context, Tagged<CompletionList>)> Callback,
Ilya Biryukovd3b04e32017-12-05 10:42:57 +0000231 llvm::Optional<StringRef> OverridenContents,
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000232 IntrusiveRefCntPtr<vfs::FileSystem> *UsedFS) {
Ilya Biryukov940901e2017-12-13 12:51:22 +0000233 using CallbackType = UniqueFunction<void(Context, Tagged<CompletionList>)>;
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000234
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000235 std::string Contents;
236 if (OverridenContents) {
237 Contents = *OverridenContents;
238 } else {
Ilya Biryukov0e27ce42017-06-13 14:15:56 +0000239 auto FileContents = DraftMgr.getDraft(File);
240 assert(FileContents.Draft &&
241 "codeComplete is called for non-added document");
242
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000243 Contents = std::move(*FileContents.Draft);
Ilya Biryukov0e27ce42017-06-13 14:15:56 +0000244 }
Ilya Biryukov38d79772017-05-16 09:38:59 +0000245
Ilya Biryukovaf0c04b2017-06-14 09:46:44 +0000246 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
Ilya Biryukoved99e4c2017-07-31 17:09:29 +0000247 if (UsedFS)
248 *UsedFS = TaggedFS.Value;
249
Ilya Biryukov02d58702017-08-01 15:51:38 +0000250 std::shared_ptr<CppFile> Resources = Units.getFile(File);
251 assert(Resources && "Calling completion on non-added file");
252
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000253 // Remember the current Preamble and use it when async task starts executing.
254 // At the point when async task starts executing, we may have a different
255 // Preamble in Resources. However, we assume the Preamble that we obtain here
256 // is reusable in completion more often.
257 std::shared_ptr<const PreambleData> Preamble =
258 Resources->getPossiblyStalePreamble();
Ilya Biryukovd3b04e32017-12-05 10:42:57 +0000259 // Copy completion options for passing them to async task handler.
260 auto CodeCompleteOpts = Opts;
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000261 // A task that will be run asynchronously.
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000262 auto Task =
263 // 'mutable' to reassign Preamble variable.
Ilya Biryukov940901e2017-12-13 12:51:22 +0000264 [=](Context Ctx, CallbackType Callback) mutable {
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000265 if (!Preamble) {
266 // Maybe we built some preamble before processing this request.
267 Preamble = Resources->getPossiblyStalePreamble();
268 }
269 // FIXME(ibiryukov): even if Preamble is non-null, we may want to check
270 // both the old and the new version in case only one of them matches.
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000271
Sam McCalla40371b2017-11-15 09:16:29 +0000272 CompletionList Result = clangd::codeComplete(
Ilya Biryukov940901e2017-12-13 12:51:22 +0000273 Ctx, File, Resources->getCompileCommand(),
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000274 Preamble ? &Preamble->Preamble : nullptr, Contents, Pos,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000275 TaggedFS.Value, PCHs, CodeCompleteOpts);
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000276
Ilya Biryukov940901e2017-12-13 12:51:22 +0000277 Callback(std::move(Ctx),
278 make_tagged(std::move(Result), std::move(TaggedFS.Tag)));
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000279 };
280
Ilya Biryukov940901e2017-12-13 12:51:22 +0000281 WorkScheduler.addToFront(std::move(Task), std::move(Ctx),
282 std::move(Callback));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000283}
Ilya Biryukovf01af682017-05-23 13:42:59 +0000284
Benjamin Krameree19f162017-10-26 12:28:13 +0000285llvm::Expected<Tagged<SignatureHelp>>
Ilya Biryukov940901e2017-12-13 12:51:22 +0000286ClangdServer::signatureHelp(const Context &Ctx, PathRef File, Position Pos,
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000287 llvm::Optional<StringRef> OverridenContents,
288 IntrusiveRefCntPtr<vfs::FileSystem> *UsedFS) {
289 std::string DraftStorage;
290 if (!OverridenContents) {
291 auto FileContents = DraftMgr.getDraft(File);
Benjamin Krameree19f162017-10-26 12:28:13 +0000292 if (!FileContents.Draft)
293 return llvm::make_error<llvm::StringError>(
294 "signatureHelp is called for non-added document",
295 llvm::errc::invalid_argument);
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000296
297 DraftStorage = std::move(*FileContents.Draft);
298 OverridenContents = DraftStorage;
299 }
300
301 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
302 if (UsedFS)
303 *UsedFS = TaggedFS.Value;
304
305 std::shared_ptr<CppFile> Resources = Units.getFile(File);
Benjamin Krameree19f162017-10-26 12:28:13 +0000306 if (!Resources)
307 return llvm::make_error<llvm::StringError>(
308 "signatureHelp is called for non-added document",
309 llvm::errc::invalid_argument);
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000310
311 auto Preamble = Resources->getPossiblyStalePreamble();
Ilya Biryukov940901e2017-12-13 12:51:22 +0000312 auto Result =
313 clangd::signatureHelp(Ctx, File, Resources->getCompileCommand(),
314 Preamble ? &Preamble->Preamble : nullptr,
315 *OverridenContents, Pos, TaggedFS.Value, PCHs);
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000316 return make_tagged(std::move(Result), TaggedFS.Tag);
317}
318
Raoul Wols212bcf82017-12-12 20:25:06 +0000319llvm::Expected<tooling::Replacements>
320ClangdServer::formatRange(StringRef Code, PathRef File, Range Rng) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000321 size_t Begin = positionToOffset(Code, Rng.start);
322 size_t Len = positionToOffset(Code, Rng.end) - Begin;
323 return formatCode(Code, File, {tooling::Range(Begin, Len)});
324}
325
Raoul Wols212bcf82017-12-12 20:25:06 +0000326llvm::Expected<tooling::Replacements> ClangdServer::formatFile(StringRef Code,
327 PathRef File) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000328 // Format everything.
Ilya Biryukovafb55542017-05-16 14:40:30 +0000329 return formatCode(Code, File, {tooling::Range(0, Code.size())});
330}
331
Raoul Wols212bcf82017-12-12 20:25:06 +0000332llvm::Expected<tooling::Replacements>
333ClangdServer::formatOnType(StringRef Code, PathRef File, Position Pos) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000334 // Look for the previous opening brace from the character position and
335 // format starting from there.
Ilya Biryukovafb55542017-05-16 14:40:30 +0000336 size_t CursorPos = positionToOffset(Code, Pos);
337 size_t PreviousLBracePos = StringRef(Code).find_last_of('{', CursorPos);
338 if (PreviousLBracePos == StringRef::npos)
339 PreviousLBracePos = CursorPos;
340 size_t Len = 1 + CursorPos - PreviousLBracePos;
341
342 return formatCode(Code, File, {tooling::Range(PreviousLBracePos, Len)});
343}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000344
Haojian Wu345099c2017-11-09 11:30:04 +0000345Expected<std::vector<tooling::Replacement>>
Ilya Biryukov940901e2017-12-13 12:51:22 +0000346ClangdServer::rename(const Context &Ctx, PathRef File, Position Pos,
347 llvm::StringRef NewName) {
Haojian Wu345099c2017-11-09 11:30:04 +0000348 std::string Code = getDocument(File);
349 std::shared_ptr<CppFile> Resources = Units.getFile(File);
350 RefactoringResultCollector ResultCollector;
351 Resources->getAST().get()->runUnderLock([&](ParsedAST *AST) {
352 const SourceManager &SourceMgr = AST->getASTContext().getSourceManager();
353 const FileEntry *FE =
354 SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
355 if (!FE)
356 return;
357 SourceLocation SourceLocationBeg =
358 clangd::getBeginningOfIdentifier(*AST, Pos, FE);
359 tooling::RefactoringRuleContext Context(
360 AST->getASTContext().getSourceManager());
361 Context.setASTContext(AST->getASTContext());
362 auto Rename = clang::tooling::RenameOccurrences::initiate(
363 Context, SourceRange(SourceLocationBeg), NewName.str());
364 if (!Rename) {
365 ResultCollector.Result = Rename.takeError();
366 return;
367 }
368 Rename->invoke(ResultCollector, Context);
369 });
370 assert(ResultCollector.Result.hasValue());
371 if (!ResultCollector.Result.getValue())
372 return ResultCollector.Result->takeError();
373
374 std::vector<tooling::Replacement> Replacements;
375 for (const tooling::AtomicChange &Change : ResultCollector.Result->get()) {
376 tooling::Replacements ChangeReps = Change.getReplacements();
377 for (const auto &Rep : ChangeReps) {
378 // FIXME: Right now we only support renaming the main file, so we drop
379 // replacements not for the main file. In the future, we might consider to
380 // support:
381 // * rename in any included header
382 // * rename only in the "main" header
383 // * provide an error if there are symbols we won't rename (e.g.
384 // std::vector)
385 // * rename globally in project
386 // * rename in open files
387 if (Rep.getFilePath() == File)
388 Replacements.push_back(Rep);
389 }
390 }
391 return Replacements;
392}
393
Ilya Biryukov38d79772017-05-16 09:38:59 +0000394std::string ClangdServer::getDocument(PathRef File) {
395 auto draft = DraftMgr.getDraft(File);
396 assert(draft.Draft && "File is not tracked, cannot get contents");
397 return *draft.Draft;
398}
399
Ilya Biryukovf01af682017-05-23 13:42:59 +0000400std::string ClangdServer::dumpAST(PathRef File) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000401 std::shared_ptr<CppFile> Resources = Units.getFile(File);
402 assert(Resources && "dumpAST is called for non-added document");
Ilya Biryukov38d79772017-05-16 09:38:59 +0000403
Ilya Biryukov02d58702017-08-01 15:51:38 +0000404 std::string Result;
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +0000405 Resources->getAST().get()->runUnderLock([&Result](ParsedAST *AST) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000406 llvm::raw_string_ostream ResultOS(Result);
407 if (AST) {
408 clangd::dumpAST(*AST, ResultOS);
409 } else {
410 ResultOS << "<no-ast>";
411 }
412 ResultOS.flush();
Ilya Biryukovf01af682017-05-23 13:42:59 +0000413 });
Ilya Biryukov02d58702017-08-01 15:51:38 +0000414 return Result;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000415}
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000416
Benjamin Krameree19f162017-10-26 12:28:13 +0000417llvm::Expected<Tagged<std::vector<Location>>>
Ilya Biryukov940901e2017-12-13 12:51:22 +0000418ClangdServer::findDefinitions(const Context &Ctx, PathRef File, Position Pos) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000419 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
420
421 std::shared_ptr<CppFile> Resources = Units.getFile(File);
Benjamin Krameree19f162017-10-26 12:28:13 +0000422 if (!Resources)
423 return llvm::make_error<llvm::StringError>(
424 "findDefinitions called on non-added file",
425 llvm::errc::invalid_argument);
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000426
427 std::vector<Location> Result;
Ilya Biryukov940901e2017-12-13 12:51:22 +0000428 Resources->getAST().get()->runUnderLock([Pos, &Result, &Ctx](ParsedAST *AST) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000429 if (!AST)
430 return;
Ilya Biryukov940901e2017-12-13 12:51:22 +0000431 Result = clangd::findDefinitions(Ctx, *AST, Pos);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000432 });
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000433 return make_tagged(std::move(Result), TaggedFS.Tag);
434}
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000435
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000436llvm::Optional<Path> ClangdServer::switchSourceHeader(PathRef Path) {
437
438 StringRef SourceExtensions[] = {".cpp", ".c", ".cc", ".cxx",
439 ".c++", ".m", ".mm"};
440 StringRef HeaderExtensions[] = {".h", ".hh", ".hpp", ".hxx", ".inc"};
441
442 StringRef PathExt = llvm::sys::path::extension(Path);
443
444 // Lookup in a list of known extensions.
445 auto SourceIter =
446 std::find_if(std::begin(SourceExtensions), std::end(SourceExtensions),
447 [&PathExt](PathRef SourceExt) {
448 return SourceExt.equals_lower(PathExt);
449 });
450 bool IsSource = SourceIter != std::end(SourceExtensions);
451
452 auto HeaderIter =
453 std::find_if(std::begin(HeaderExtensions), std::end(HeaderExtensions),
454 [&PathExt](PathRef HeaderExt) {
455 return HeaderExt.equals_lower(PathExt);
456 });
457
458 bool IsHeader = HeaderIter != std::end(HeaderExtensions);
459
460 // We can only switch between extensions known extensions.
461 if (!IsSource && !IsHeader)
462 return llvm::None;
463
464 // Array to lookup extensions for the switch. An opposite of where original
465 // extension was found.
466 ArrayRef<StringRef> NewExts;
467 if (IsSource)
468 NewExts = HeaderExtensions;
469 else
470 NewExts = SourceExtensions;
471
472 // Storage for the new path.
473 SmallString<128> NewPath = StringRef(Path);
474
475 // Instance of vfs::FileSystem, used for file existence checks.
476 auto FS = FSProvider.getTaggedFileSystem(Path).Value;
477
478 // Loop through switched extension candidates.
479 for (StringRef NewExt : NewExts) {
480 llvm::sys::path::replace_extension(NewPath, NewExt);
481 if (FS->exists(NewPath))
482 return NewPath.str().str(); // First str() to convert from SmallString to
483 // StringRef, second to convert from StringRef
484 // to std::string
Ilya Biryukov33334942017-10-06 14:39:39 +0000485
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000486 // Also check NewExt in upper-case, just in case.
487 llvm::sys::path::replace_extension(NewPath, NewExt.upper());
488 if (FS->exists(NewPath))
489 return NewPath.str().str();
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000490 }
491
492 return llvm::None;
493}
494
Raoul Wols212bcf82017-12-12 20:25:06 +0000495llvm::Expected<tooling::Replacements>
496ClangdServer::formatCode(llvm::StringRef Code, PathRef File,
497 ArrayRef<tooling::Range> Ranges) {
498 // Call clang-format.
499 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
500 auto StyleOrError =
501 format::getStyle("file", File, "LLVM", Code, TaggedFS.Value.get());
502 if (!StyleOrError) {
503 return StyleOrError.takeError();
504 } else {
505 return format::reformat(StyleOrError.get(), Code, Ranges, File);
506 }
507}
508
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000509llvm::Expected<Tagged<std::vector<DocumentHighlight>>>
Ilya Biryukov940901e2017-12-13 12:51:22 +0000510ClangdServer::findDocumentHighlights(const Context &Ctx, PathRef File,
511 Position Pos) {
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000512 auto FileContents = DraftMgr.getDraft(File);
513 if (!FileContents.Draft)
514 return llvm::make_error<llvm::StringError>(
515 "findDocumentHighlights called on non-added file",
516 llvm::errc::invalid_argument);
517
518 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
519
520 std::shared_ptr<CppFile> Resources = Units.getFile(File);
521 if (!Resources)
522 return llvm::make_error<llvm::StringError>(
523 "findDocumentHighlights called on non-added file",
524 llvm::errc::invalid_argument);
525
526 std::vector<DocumentHighlight> Result;
527 llvm::Optional<llvm::Error> Err;
Ilya Biryukov940901e2017-12-13 12:51:22 +0000528 Resources->getAST().get()->runUnderLock([Pos, &Ctx, &Err,
529 &Result](ParsedAST *AST) {
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000530 if (!AST) {
531 Err = llvm::make_error<llvm::StringError>("Invalid AST",
532 llvm::errc::invalid_argument);
533 return;
534 }
Ilya Biryukov940901e2017-12-13 12:51:22 +0000535 Result = clangd::findDocumentHighlights(Ctx, *AST, Pos);
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000536 });
537
538 if (Err)
539 return std::move(*Err);
540 return make_tagged(Result, TaggedFS.Tag);
541}
542
Ilya Biryukov940901e2017-12-13 12:51:22 +0000543std::future<Context> ClangdServer::scheduleReparseAndDiags(
544 Context Ctx, PathRef File, VersionedDraft Contents,
545 std::shared_ptr<CppFile> Resources,
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000546 Tagged<IntrusiveRefCntPtr<vfs::FileSystem>> TaggedFS) {
547
548 assert(Contents.Draft && "Draft must have contents");
Ilya Biryukov940901e2017-12-13 12:51:22 +0000549 UniqueFunction<llvm::Optional<std::vector<DiagWithFixIts>>(const Context &)>
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000550 DeferredRebuild =
551 Resources->deferRebuild(*Contents.Draft, TaggedFS.Value);
Ilya Biryukov940901e2017-12-13 12:51:22 +0000552 std::promise<Context> DonePromise;
553 std::future<Context> DoneFuture = DonePromise.get_future();
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000554
555 DocVersion Version = Contents.Version;
556 Path FileStr = File;
557 VFSTag Tag = TaggedFS.Tag;
558 auto ReparseAndPublishDiags =
559 [this, FileStr, Version,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000560 Tag](UniqueFunction<llvm::Optional<std::vector<DiagWithFixIts>>(
561 const Context &)>
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000562 DeferredRebuild,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000563 std::promise<Context> DonePromise, Context Ctx) -> void {
564 auto Guard = onScopeExit([&]() { DonePromise.set_value(std::move(Ctx)); });
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000565
566 auto CurrentVersion = DraftMgr.getVersion(FileStr);
567 if (CurrentVersion != Version)
568 return; // This request is outdated
569
Ilya Biryukov940901e2017-12-13 12:51:22 +0000570 auto Diags = DeferredRebuild(Ctx);
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000571 if (!Diags)
572 return; // A new reparse was requested before this one completed.
Ilya Biryukov47f22022017-09-20 12:58:55 +0000573
574 // We need to serialize access to resulting diagnostics to avoid calling
575 // `onDiagnosticsReady` in the wrong order.
576 std::lock_guard<std::mutex> DiagsLock(DiagnosticsMutex);
577 DocVersion &LastReportedDiagsVersion = ReportedDiagnosticVersions[FileStr];
578 // FIXME(ibiryukov): get rid of '<' comparison here. In the current
579 // implementation diagnostics will not be reported after version counters'
580 // overflow. This should not happen in practice, since DocVersion is a
581 // 64-bit unsigned integer.
582 if (Version < LastReportedDiagsVersion)
583 return;
584 LastReportedDiagsVersion = Version;
585
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000586 DiagConsumer.onDiagnosticsReady(FileStr,
587 make_tagged(std::move(*Diags), Tag));
588 };
589
590 WorkScheduler.addToFront(std::move(ReparseAndPublishDiags),
Ilya Biryukov940901e2017-12-13 12:51:22 +0000591 std::move(DeferredRebuild), std::move(DonePromise),
592 std::move(Ctx));
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000593 return DoneFuture;
594}
595
Ilya Biryukov940901e2017-12-13 12:51:22 +0000596std::future<Context>
597ClangdServer::scheduleCancelRebuild(Context Ctx,
598 std::shared_ptr<CppFile> Resources) {
599 std::promise<Context> DonePromise;
600 std::future<Context> DoneFuture = DonePromise.get_future();
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000601 if (!Resources) {
602 // No need to schedule any cleanup.
Ilya Biryukov940901e2017-12-13 12:51:22 +0000603 DonePromise.set_value(std::move(Ctx));
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000604 return DoneFuture;
605 }
606
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000607 UniqueFunction<void()> DeferredCancel = Resources->deferCancelRebuild();
Ilya Biryukov940901e2017-12-13 12:51:22 +0000608 auto CancelReparses = [Resources](std::promise<Context> DonePromise,
609 UniqueFunction<void()> DeferredCancel,
610 Context Ctx) {
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000611 DeferredCancel();
Ilya Biryukov940901e2017-12-13 12:51:22 +0000612 DonePromise.set_value(std::move(Ctx));
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000613 };
614 WorkScheduler.addToFront(std::move(CancelReparses), std::move(DonePromise),
Ilya Biryukov940901e2017-12-13 12:51:22 +0000615 std::move(DeferredCancel), std::move(Ctx));
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000616 return DoneFuture;
617}
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000618
619void ClangdServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
620 // FIXME: Do nothing for now. This will be used for indexing and potentially
621 // invalidating other caches.
622}