blob: e7c9c7a5148f44ac780a7480a0485f58edcbe31b [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"
Sam McCalla66d2cb2017-12-19 17:06:07 +000011#include "CodeComplete.h"
Sam McCallb536a2a2017-12-19 12:23:48 +000012#include "SourceCode.h"
Sam McCalla66d2cb2017-12-19 17:06:07 +000013#include "XRefs.h"
Ilya Biryukovafb55542017-05-16 14:40:30 +000014#include "clang/Format/Format.h"
Ilya Biryukov38d79772017-05-16 09:38:59 +000015#include "clang/Frontend/CompilerInstance.h"
16#include "clang/Frontend/CompilerInvocation.h"
17#include "clang/Tooling/CompilationDatabase.h"
Ilya Biryukov9e11c4c2017-11-15 18:04:56 +000018#include "clang/Tooling/Refactoring/RefactoringResultConsumer.h"
19#include "clang/Tooling/Refactoring/Rename/RenamingAction.h"
Ilya Biryukovafb55542017-05-16 14:40:30 +000020#include "llvm/ADT/ArrayRef.h"
Benjamin Krameree19f162017-10-26 12:28:13 +000021#include "llvm/Support/Errc.h"
Ilya Biryukov38d79772017-05-16 09:38:59 +000022#include "llvm/Support/FileSystem.h"
Sam McCall8567cb32017-11-02 09:21:51 +000023#include "llvm/Support/FormatProviders.h"
24#include "llvm/Support/FormatVariadic.h"
Marc-Andre Laperle37de9712017-09-27 15:31:17 +000025#include "llvm/Support/Path.h"
Ilya Biryukovf01af682017-05-23 13:42:59 +000026#include "llvm/Support/raw_ostream.h"
27#include <future>
Ilya Biryukov38d79772017-05-16 09:38:59 +000028
Ilya Biryukov2f314102017-05-16 10:06:20 +000029using namespace clang;
Ilya Biryukov38d79772017-05-16 09:38:59 +000030using namespace clang::clangd;
31
Ilya Biryukovafb55542017-05-16 14:40:30 +000032namespace {
33
Ilya Biryukova46f7a92017-06-28 10:34:50 +000034std::string getStandardResourceDir() {
35 static int Dummy; // Just an address in this process.
36 return CompilerInvocation::GetResourcesPath("clangd", (void *)&Dummy);
37}
38
Haojian Wu345099c2017-11-09 11:30:04 +000039class RefactoringResultCollector final
40 : public tooling::RefactoringResultConsumer {
41public:
42 void handleError(llvm::Error Err) override {
43 assert(!Result.hasValue());
44 // FIXME: figure out a way to return better message for DiagnosticError.
45 // clangd uses llvm::toString to convert the Err to string, however, for
46 // DiagnosticError, only "clang diagnostic" will be generated.
47 Result = std::move(Err);
48 }
49
50 // Using the handle(SymbolOccurrences) from parent class.
51 using tooling::RefactoringResultConsumer::handle;
52
53 void handle(tooling::AtomicChanges SourceReplacements) override {
54 assert(!Result.hasValue());
55 Result = std::move(SourceReplacements);
56 }
57
58 Optional<Expected<tooling::AtomicChanges>> Result;
59};
60
Ilya Biryukovafb55542017-05-16 14:40:30 +000061} // namespace
62
Ilya Biryukov22602992017-05-30 15:11:02 +000063Tagged<IntrusiveRefCntPtr<vfs::FileSystem>>
Ilya Biryukovaf0c04b2017-06-14 09:46:44 +000064RealFileSystemProvider::getTaggedFileSystem(PathRef File) {
Ilya Biryukov22602992017-05-30 15:11:02 +000065 return make_tagged(vfs::getRealFileSystem(), VFSTag());
Ilya Biryukov0f62ed22017-05-26 12:26:51 +000066}
67
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +000068unsigned clangd::getDefaultAsyncThreadsCount() {
69 unsigned HardwareConcurrency = std::thread::hardware_concurrency();
70 // C++ standard says that hardware_concurrency()
71 // may return 0, fallback to 1 worker thread in
72 // that case.
73 if (HardwareConcurrency == 0)
74 return 1;
75 return HardwareConcurrency;
76}
77
78ClangdScheduler::ClangdScheduler(unsigned AsyncThreadsCount)
79 : RunSynchronously(AsyncThreadsCount == 0) {
Ilya Biryukov38d79772017-05-16 09:38:59 +000080 if (RunSynchronously) {
81 // Don't start the worker thread if we're running synchronously
82 return;
83 }
84
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +000085 Workers.reserve(AsyncThreadsCount);
86 for (unsigned I = 0; I < AsyncThreadsCount; ++I) {
Sam McCall8567cb32017-11-02 09:21:51 +000087 Workers.push_back(std::thread([this, I]() {
88 llvm::set_thread_name(llvm::formatv("scheduler/{0}", I));
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +000089 while (true) {
Ilya Biryukov08e6ccb2017-10-09 16:26:26 +000090 UniqueFunction<void()> Request;
Ilya Biryukov38d79772017-05-16 09:38:59 +000091
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +000092 // Pick request from the queue
93 {
94 std::unique_lock<std::mutex> Lock(Mutex);
95 // Wait for more requests.
96 RequestCV.wait(Lock,
97 [this] { return !RequestQueue.empty() || Done; });
98 if (Done)
99 return;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000100
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000101 assert(!RequestQueue.empty() && "RequestQueue was empty");
Ilya Biryukov38d79772017-05-16 09:38:59 +0000102
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000103 // We process requests starting from the front of the queue. Users of
104 // ClangdScheduler have a way to prioritise their requests by putting
105 // them to the either side of the queue (using either addToEnd or
106 // addToFront).
107 Request = std::move(RequestQueue.front());
108 RequestQueue.pop_front();
109 } // unlock Mutex
Ilya Biryukov38d79772017-05-16 09:38:59 +0000110
Ilya Biryukov08e6ccb2017-10-09 16:26:26 +0000111 Request();
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000112 }
113 }));
114 }
Ilya Biryukov38d79772017-05-16 09:38:59 +0000115}
116
117ClangdScheduler::~ClangdScheduler() {
118 if (RunSynchronously)
119 return; // no worker thread is running in that case
120
121 {
122 std::lock_guard<std::mutex> Lock(Mutex);
123 // Wake up the worker thread
124 Done = true;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000125 } // unlock Mutex
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000126 RequestCV.notify_all();
127
128 for (auto &Worker : Workers)
129 Worker.join();
Ilya Biryukov38d79772017-05-16 09:38:59 +0000130}
131
Sam McCalladccab62017-11-23 16:58:22 +0000132ClangdServer::ClangdServer(GlobalCompilationDatabase &CDB,
133 DiagnosticsConsumer &DiagConsumer,
134 FileSystemProvider &FSProvider,
135 unsigned AsyncThreadsCount,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000136 bool StorePreamblesInMemory,
Eric Liubfac8f72017-12-19 18:00:37 +0000137 bool BuildDynamicSymbolIndex,
Sam McCalladccab62017-11-23 16:58:22 +0000138 llvm::Optional<StringRef> ResourceDir)
Ilya Biryukov940901e2017-12-13 12:51:22 +0000139 : CDB(CDB), DiagConsumer(DiagConsumer), FSProvider(FSProvider),
Eric Liubfac8f72017-12-19 18:00:37 +0000140 FileIdx(BuildDynamicSymbolIndex ? new FileIndex() : nullptr),
141 // Pass a callback into `Units` to extract symbols from a newly parsed
142 // file and rebuild the file index synchronously each time an AST is
143 // parsed.
144 // FIXME(ioeric): this can be slow and we may be able to index on less
145 // critical paths.
146 Units(FileIdx
147 ? [this](const Context &Ctx, PathRef Path,
148 ParsedAST *AST) { FileIdx->update(Ctx, Path, AST); }
149 : ASTParsedCallback()),
Ilya Biryukova46f7a92017-06-28 10:34:50 +0000150 ResourceDir(ResourceDir ? ResourceDir->str() : getStandardResourceDir()),
Ilya Biryukov38d79772017-05-16 09:38:59 +0000151 PCHs(std::make_shared<PCHContainerOperations>()),
Ilya Biryukove9eb7f02017-11-16 16:25:18 +0000152 StorePreamblesInMemory(StorePreamblesInMemory),
Ilya Biryukovd3b04e32017-12-05 10:42:57 +0000153 WorkScheduler(AsyncThreadsCount) {}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000154
Marc-Andre Laperle37de9712017-09-27 15:31:17 +0000155void ClangdServer::setRootPath(PathRef RootPath) {
156 std::string NewRootPath = llvm::sys::path::convert_to_slash(
157 RootPath, llvm::sys::path::Style::posix);
158 if (llvm::sys::fs::is_directory(NewRootPath))
159 this->RootPath = NewRootPath;
160}
161
Ilya Biryukov940901e2017-12-13 12:51:22 +0000162std::future<Context> ClangdServer::addDocument(Context Ctx, PathRef File,
163 StringRef Contents) {
Ilya Biryukovf01af682017-05-23 13:42:59 +0000164 DocVersion Version = DraftMgr.updateDraft(File, Contents);
Ilya Biryukovf01af682017-05-23 13:42:59 +0000165
Ilya Biryukov02d58702017-08-01 15:51:38 +0000166 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
Ilya Biryukove9eb7f02017-11-16 16:25:18 +0000167 std::shared_ptr<CppFile> Resources = Units.getOrCreateFile(
Ilya Biryukov940901e2017-12-13 12:51:22 +0000168 File, ResourceDir, CDB, StorePreamblesInMemory, PCHs);
169 return scheduleReparseAndDiags(std::move(Ctx), File,
170 VersionedDraft{Version, Contents.str()},
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000171 std::move(Resources), std::move(TaggedFS));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000172}
173
Ilya Biryukov940901e2017-12-13 12:51:22 +0000174std::future<Context> ClangdServer::removeDocument(Context Ctx, PathRef File) {
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000175 DraftMgr.removeDraft(File);
176 std::shared_ptr<CppFile> Resources = Units.removeIfPresent(File);
Ilya Biryukov940901e2017-12-13 12:51:22 +0000177 return scheduleCancelRebuild(std::move(Ctx), std::move(Resources));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000178}
179
Ilya Biryukov940901e2017-12-13 12:51:22 +0000180std::future<Context> ClangdServer::forceReparse(Context Ctx, PathRef File) {
Ilya Biryukov91dbf5b2017-08-14 08:37:32 +0000181 auto FileContents = DraftMgr.getDraft(File);
182 assert(FileContents.Draft &&
183 "forceReparse() was called for non-added document");
184
185 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
Ilya Biryukove9eb7f02017-11-16 16:25:18 +0000186 auto Recreated = Units.recreateFileIfCompileCommandChanged(
Ilya Biryukov940901e2017-12-13 12:51:22 +0000187 File, ResourceDir, CDB, StorePreamblesInMemory, PCHs);
Ilya Biryukov91dbf5b2017-08-14 08:37:32 +0000188
189 // Note that std::future from this cleanup action is ignored.
Ilya Biryukov940901e2017-12-13 12:51:22 +0000190 scheduleCancelRebuild(Ctx.clone(), std::move(Recreated.RemovedFile));
Ilya Biryukov91dbf5b2017-08-14 08:37:32 +0000191 // Schedule a reparse.
Ilya Biryukov940901e2017-12-13 12:51:22 +0000192 return scheduleReparseAndDiags(std::move(Ctx), File, std::move(FileContents),
Ilya Biryukov91dbf5b2017-08-14 08:37:32 +0000193 std::move(Recreated.FileInCollection),
194 std::move(TaggedFS));
Ilya Biryukov0f62ed22017-05-26 12:26:51 +0000195}
196
Ilya Biryukov940901e2017-12-13 12:51:22 +0000197std::future<std::pair<Context, Tagged<CompletionList>>>
198ClangdServer::codeComplete(Context Ctx, PathRef File, Position Pos,
Ilya Biryukovd3b04e32017-12-05 10:42:57 +0000199 const clangd::CodeCompleteOptions &Opts,
Ilya Biryukoved99e4c2017-07-31 17:09:29 +0000200 llvm::Optional<StringRef> OverridenContents,
201 IntrusiveRefCntPtr<vfs::FileSystem> *UsedFS) {
Ilya Biryukov940901e2017-12-13 12:51:22 +0000202 using ResultType = std::pair<Context, Tagged<CompletionList>>;
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000203
204 std::promise<ResultType> ResultPromise;
205
Ilya Biryukov940901e2017-12-13 12:51:22 +0000206 auto Callback = [](std::promise<ResultType> ResultPromise, Context Ctx,
207 Tagged<CompletionList> Result) -> void {
208 ResultPromise.set_value({std::move(Ctx), std::move(Result)});
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000209 };
210
211 std::future<ResultType> ResultFuture = ResultPromise.get_future();
Ilya Biryukov940901e2017-12-13 12:51:22 +0000212 codeComplete(std::move(Ctx), File, Pos, Opts,
213 BindWithForward(Callback, std::move(ResultPromise)),
214 OverridenContents, UsedFS);
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000215 return ResultFuture;
216}
217
218void ClangdServer::codeComplete(
Ilya Biryukov940901e2017-12-13 12:51:22 +0000219 Context Ctx, PathRef File, Position Pos,
220 const clangd::CodeCompleteOptions &Opts,
221 UniqueFunction<void(Context, Tagged<CompletionList>)> Callback,
Ilya Biryukovd3b04e32017-12-05 10:42:57 +0000222 llvm::Optional<StringRef> OverridenContents,
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000223 IntrusiveRefCntPtr<vfs::FileSystem> *UsedFS) {
Ilya Biryukov940901e2017-12-13 12:51:22 +0000224 using CallbackType = UniqueFunction<void(Context, Tagged<CompletionList>)>;
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000225
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000226 std::string Contents;
227 if (OverridenContents) {
228 Contents = *OverridenContents;
229 } else {
Ilya Biryukov0e27ce42017-06-13 14:15:56 +0000230 auto FileContents = DraftMgr.getDraft(File);
231 assert(FileContents.Draft &&
232 "codeComplete is called for non-added document");
233
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000234 Contents = std::move(*FileContents.Draft);
Ilya Biryukov0e27ce42017-06-13 14:15:56 +0000235 }
Ilya Biryukov38d79772017-05-16 09:38:59 +0000236
Ilya Biryukovaf0c04b2017-06-14 09:46:44 +0000237 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
Ilya Biryukoved99e4c2017-07-31 17:09:29 +0000238 if (UsedFS)
239 *UsedFS = TaggedFS.Value;
240
Ilya Biryukov02d58702017-08-01 15:51:38 +0000241 std::shared_ptr<CppFile> Resources = Units.getFile(File);
242 assert(Resources && "Calling completion on non-added file");
243
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000244 // Remember the current Preamble and use it when async task starts executing.
245 // At the point when async task starts executing, we may have a different
246 // Preamble in Resources. However, we assume the Preamble that we obtain here
247 // is reusable in completion more often.
248 std::shared_ptr<const PreambleData> Preamble =
249 Resources->getPossiblyStalePreamble();
Ilya Biryukovd3b04e32017-12-05 10:42:57 +0000250 // Copy completion options for passing them to async task handler.
251 auto CodeCompleteOpts = Opts;
Eric Liubfac8f72017-12-19 18:00:37 +0000252 if (FileIdx)
253 CodeCompleteOpts.Index = FileIdx.get();
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000254 // A task that will be run asynchronously.
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000255 auto Task =
256 // 'mutable' to reassign Preamble variable.
Ilya Biryukov940901e2017-12-13 12:51:22 +0000257 [=](Context Ctx, CallbackType Callback) mutable {
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000258 if (!Preamble) {
259 // Maybe we built some preamble before processing this request.
260 Preamble = Resources->getPossiblyStalePreamble();
261 }
262 // FIXME(ibiryukov): even if Preamble is non-null, we may want to check
263 // both the old and the new version in case only one of them matches.
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000264
Sam McCalla40371b2017-11-15 09:16:29 +0000265 CompletionList Result = clangd::codeComplete(
Ilya Biryukov940901e2017-12-13 12:51:22 +0000266 Ctx, File, Resources->getCompileCommand(),
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000267 Preamble ? &Preamble->Preamble : nullptr, Contents, Pos,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000268 TaggedFS.Value, PCHs, CodeCompleteOpts);
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000269
Ilya Biryukov940901e2017-12-13 12:51:22 +0000270 Callback(std::move(Ctx),
271 make_tagged(std::move(Result), std::move(TaggedFS.Tag)));
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000272 };
273
Ilya Biryukov940901e2017-12-13 12:51:22 +0000274 WorkScheduler.addToFront(std::move(Task), std::move(Ctx),
275 std::move(Callback));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000276}
Ilya Biryukovf01af682017-05-23 13:42:59 +0000277
Benjamin Krameree19f162017-10-26 12:28:13 +0000278llvm::Expected<Tagged<SignatureHelp>>
Ilya Biryukov940901e2017-12-13 12:51:22 +0000279ClangdServer::signatureHelp(const Context &Ctx, PathRef File, Position Pos,
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000280 llvm::Optional<StringRef> OverridenContents,
281 IntrusiveRefCntPtr<vfs::FileSystem> *UsedFS) {
282 std::string DraftStorage;
283 if (!OverridenContents) {
284 auto FileContents = DraftMgr.getDraft(File);
Benjamin Krameree19f162017-10-26 12:28:13 +0000285 if (!FileContents.Draft)
286 return llvm::make_error<llvm::StringError>(
287 "signatureHelp is called for non-added document",
288 llvm::errc::invalid_argument);
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000289
290 DraftStorage = std::move(*FileContents.Draft);
291 OverridenContents = DraftStorage;
292 }
293
294 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
295 if (UsedFS)
296 *UsedFS = TaggedFS.Value;
297
298 std::shared_ptr<CppFile> Resources = Units.getFile(File);
Benjamin Krameree19f162017-10-26 12:28:13 +0000299 if (!Resources)
300 return llvm::make_error<llvm::StringError>(
301 "signatureHelp is called for non-added document",
302 llvm::errc::invalid_argument);
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000303
304 auto Preamble = Resources->getPossiblyStalePreamble();
Ilya Biryukov940901e2017-12-13 12:51:22 +0000305 auto Result =
306 clangd::signatureHelp(Ctx, File, Resources->getCompileCommand(),
307 Preamble ? &Preamble->Preamble : nullptr,
308 *OverridenContents, Pos, TaggedFS.Value, PCHs);
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000309 return make_tagged(std::move(Result), TaggedFS.Tag);
310}
311
Raoul Wols212bcf82017-12-12 20:25:06 +0000312llvm::Expected<tooling::Replacements>
313ClangdServer::formatRange(StringRef Code, PathRef File, Range Rng) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000314 size_t Begin = positionToOffset(Code, Rng.start);
315 size_t Len = positionToOffset(Code, Rng.end) - Begin;
316 return formatCode(Code, File, {tooling::Range(Begin, Len)});
317}
318
Raoul Wols212bcf82017-12-12 20:25:06 +0000319llvm::Expected<tooling::Replacements> ClangdServer::formatFile(StringRef Code,
320 PathRef File) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000321 // Format everything.
Ilya Biryukovafb55542017-05-16 14:40:30 +0000322 return formatCode(Code, File, {tooling::Range(0, Code.size())});
323}
324
Raoul Wols212bcf82017-12-12 20:25:06 +0000325llvm::Expected<tooling::Replacements>
326ClangdServer::formatOnType(StringRef Code, PathRef File, Position Pos) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000327 // Look for the previous opening brace from the character position and
328 // format starting from there.
Ilya Biryukovafb55542017-05-16 14:40:30 +0000329 size_t CursorPos = positionToOffset(Code, Pos);
330 size_t PreviousLBracePos = StringRef(Code).find_last_of('{', CursorPos);
331 if (PreviousLBracePos == StringRef::npos)
332 PreviousLBracePos = CursorPos;
Sam McCallb536a2a2017-12-19 12:23:48 +0000333 size_t Len = CursorPos - PreviousLBracePos;
Ilya Biryukovafb55542017-05-16 14:40:30 +0000334
335 return formatCode(Code, File, {tooling::Range(PreviousLBracePos, Len)});
336}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000337
Haojian Wu345099c2017-11-09 11:30:04 +0000338Expected<std::vector<tooling::Replacement>>
Ilya Biryukov940901e2017-12-13 12:51:22 +0000339ClangdServer::rename(const Context &Ctx, PathRef File, Position Pos,
340 llvm::StringRef NewName) {
Haojian Wu345099c2017-11-09 11:30:04 +0000341 std::string Code = getDocument(File);
342 std::shared_ptr<CppFile> Resources = Units.getFile(File);
343 RefactoringResultCollector ResultCollector;
344 Resources->getAST().get()->runUnderLock([&](ParsedAST *AST) {
345 const SourceManager &SourceMgr = AST->getASTContext().getSourceManager();
346 const FileEntry *FE =
347 SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
348 if (!FE)
349 return;
350 SourceLocation SourceLocationBeg =
351 clangd::getBeginningOfIdentifier(*AST, Pos, FE);
352 tooling::RefactoringRuleContext Context(
353 AST->getASTContext().getSourceManager());
354 Context.setASTContext(AST->getASTContext());
355 auto Rename = clang::tooling::RenameOccurrences::initiate(
356 Context, SourceRange(SourceLocationBeg), NewName.str());
357 if (!Rename) {
358 ResultCollector.Result = Rename.takeError();
359 return;
360 }
361 Rename->invoke(ResultCollector, Context);
362 });
363 assert(ResultCollector.Result.hasValue());
364 if (!ResultCollector.Result.getValue())
365 return ResultCollector.Result->takeError();
366
367 std::vector<tooling::Replacement> Replacements;
368 for (const tooling::AtomicChange &Change : ResultCollector.Result->get()) {
369 tooling::Replacements ChangeReps = Change.getReplacements();
370 for (const auto &Rep : ChangeReps) {
371 // FIXME: Right now we only support renaming the main file, so we drop
372 // replacements not for the main file. In the future, we might consider to
373 // support:
374 // * rename in any included header
375 // * rename only in the "main" header
376 // * provide an error if there are symbols we won't rename (e.g.
377 // std::vector)
378 // * rename globally in project
379 // * rename in open files
380 if (Rep.getFilePath() == File)
381 Replacements.push_back(Rep);
382 }
383 }
384 return Replacements;
385}
386
Ilya Biryukov38d79772017-05-16 09:38:59 +0000387std::string ClangdServer::getDocument(PathRef File) {
388 auto draft = DraftMgr.getDraft(File);
389 assert(draft.Draft && "File is not tracked, cannot get contents");
390 return *draft.Draft;
391}
392
Ilya Biryukovf01af682017-05-23 13:42:59 +0000393std::string ClangdServer::dumpAST(PathRef File) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000394 std::shared_ptr<CppFile> Resources = Units.getFile(File);
395 assert(Resources && "dumpAST is called for non-added document");
Ilya Biryukov38d79772017-05-16 09:38:59 +0000396
Ilya Biryukov02d58702017-08-01 15:51:38 +0000397 std::string Result;
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +0000398 Resources->getAST().get()->runUnderLock([&Result](ParsedAST *AST) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000399 llvm::raw_string_ostream ResultOS(Result);
400 if (AST) {
401 clangd::dumpAST(*AST, ResultOS);
402 } else {
403 ResultOS << "<no-ast>";
404 }
405 ResultOS.flush();
Ilya Biryukovf01af682017-05-23 13:42:59 +0000406 });
Ilya Biryukov02d58702017-08-01 15:51:38 +0000407 return Result;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000408}
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000409
Benjamin Krameree19f162017-10-26 12:28:13 +0000410llvm::Expected<Tagged<std::vector<Location>>>
Ilya Biryukov940901e2017-12-13 12:51:22 +0000411ClangdServer::findDefinitions(const Context &Ctx, PathRef File, Position Pos) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000412 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
413
414 std::shared_ptr<CppFile> Resources = Units.getFile(File);
Benjamin Krameree19f162017-10-26 12:28:13 +0000415 if (!Resources)
416 return llvm::make_error<llvm::StringError>(
417 "findDefinitions called on non-added file",
418 llvm::errc::invalid_argument);
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000419
420 std::vector<Location> Result;
Ilya Biryukov940901e2017-12-13 12:51:22 +0000421 Resources->getAST().get()->runUnderLock([Pos, &Result, &Ctx](ParsedAST *AST) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000422 if (!AST)
423 return;
Ilya Biryukov940901e2017-12-13 12:51:22 +0000424 Result = clangd::findDefinitions(Ctx, *AST, Pos);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000425 });
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000426 return make_tagged(std::move(Result), TaggedFS.Tag);
427}
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000428
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000429llvm::Optional<Path> ClangdServer::switchSourceHeader(PathRef Path) {
430
431 StringRef SourceExtensions[] = {".cpp", ".c", ".cc", ".cxx",
432 ".c++", ".m", ".mm"};
433 StringRef HeaderExtensions[] = {".h", ".hh", ".hpp", ".hxx", ".inc"};
434
435 StringRef PathExt = llvm::sys::path::extension(Path);
436
437 // Lookup in a list of known extensions.
438 auto SourceIter =
439 std::find_if(std::begin(SourceExtensions), std::end(SourceExtensions),
440 [&PathExt](PathRef SourceExt) {
441 return SourceExt.equals_lower(PathExt);
442 });
443 bool IsSource = SourceIter != std::end(SourceExtensions);
444
445 auto HeaderIter =
446 std::find_if(std::begin(HeaderExtensions), std::end(HeaderExtensions),
447 [&PathExt](PathRef HeaderExt) {
448 return HeaderExt.equals_lower(PathExt);
449 });
450
451 bool IsHeader = HeaderIter != std::end(HeaderExtensions);
452
453 // We can only switch between extensions known extensions.
454 if (!IsSource && !IsHeader)
455 return llvm::None;
456
457 // Array to lookup extensions for the switch. An opposite of where original
458 // extension was found.
459 ArrayRef<StringRef> NewExts;
460 if (IsSource)
461 NewExts = HeaderExtensions;
462 else
463 NewExts = SourceExtensions;
464
465 // Storage for the new path.
466 SmallString<128> NewPath = StringRef(Path);
467
468 // Instance of vfs::FileSystem, used for file existence checks.
469 auto FS = FSProvider.getTaggedFileSystem(Path).Value;
470
471 // Loop through switched extension candidates.
472 for (StringRef NewExt : NewExts) {
473 llvm::sys::path::replace_extension(NewPath, NewExt);
474 if (FS->exists(NewPath))
475 return NewPath.str().str(); // First str() to convert from SmallString to
476 // StringRef, second to convert from StringRef
477 // to std::string
Ilya Biryukov33334942017-10-06 14:39:39 +0000478
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000479 // Also check NewExt in upper-case, just in case.
480 llvm::sys::path::replace_extension(NewPath, NewExt.upper());
481 if (FS->exists(NewPath))
482 return NewPath.str().str();
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000483 }
484
485 return llvm::None;
486}
487
Raoul Wols212bcf82017-12-12 20:25:06 +0000488llvm::Expected<tooling::Replacements>
489ClangdServer::formatCode(llvm::StringRef Code, PathRef File,
490 ArrayRef<tooling::Range> Ranges) {
491 // Call clang-format.
492 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
493 auto StyleOrError =
494 format::getStyle("file", File, "LLVM", Code, TaggedFS.Value.get());
495 if (!StyleOrError) {
496 return StyleOrError.takeError();
497 } else {
498 return format::reformat(StyleOrError.get(), Code, Ranges, File);
499 }
500}
501
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000502llvm::Expected<Tagged<std::vector<DocumentHighlight>>>
Ilya Biryukov940901e2017-12-13 12:51:22 +0000503ClangdServer::findDocumentHighlights(const Context &Ctx, PathRef File,
504 Position Pos) {
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000505 auto FileContents = DraftMgr.getDraft(File);
506 if (!FileContents.Draft)
507 return llvm::make_error<llvm::StringError>(
508 "findDocumentHighlights called on non-added file",
509 llvm::errc::invalid_argument);
510
511 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
512
513 std::shared_ptr<CppFile> Resources = Units.getFile(File);
514 if (!Resources)
515 return llvm::make_error<llvm::StringError>(
516 "findDocumentHighlights called on non-added file",
517 llvm::errc::invalid_argument);
518
519 std::vector<DocumentHighlight> Result;
520 llvm::Optional<llvm::Error> Err;
Ilya Biryukov940901e2017-12-13 12:51:22 +0000521 Resources->getAST().get()->runUnderLock([Pos, &Ctx, &Err,
522 &Result](ParsedAST *AST) {
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000523 if (!AST) {
524 Err = llvm::make_error<llvm::StringError>("Invalid AST",
525 llvm::errc::invalid_argument);
526 return;
527 }
Ilya Biryukov940901e2017-12-13 12:51:22 +0000528 Result = clangd::findDocumentHighlights(Ctx, *AST, Pos);
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000529 });
530
531 if (Err)
532 return std::move(*Err);
533 return make_tagged(Result, TaggedFS.Tag);
534}
535
Ilya Biryukov940901e2017-12-13 12:51:22 +0000536std::future<Context> ClangdServer::scheduleReparseAndDiags(
537 Context Ctx, PathRef File, VersionedDraft Contents,
538 std::shared_ptr<CppFile> Resources,
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000539 Tagged<IntrusiveRefCntPtr<vfs::FileSystem>> TaggedFS) {
540
541 assert(Contents.Draft && "Draft must have contents");
Ilya Biryukov940901e2017-12-13 12:51:22 +0000542 UniqueFunction<llvm::Optional<std::vector<DiagWithFixIts>>(const Context &)>
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000543 DeferredRebuild =
544 Resources->deferRebuild(*Contents.Draft, TaggedFS.Value);
Ilya Biryukov940901e2017-12-13 12:51:22 +0000545 std::promise<Context> DonePromise;
546 std::future<Context> DoneFuture = DonePromise.get_future();
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000547
548 DocVersion Version = Contents.Version;
549 Path FileStr = File;
550 VFSTag Tag = TaggedFS.Tag;
551 auto ReparseAndPublishDiags =
552 [this, FileStr, Version,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000553 Tag](UniqueFunction<llvm::Optional<std::vector<DiagWithFixIts>>(
554 const Context &)>
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000555 DeferredRebuild,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000556 std::promise<Context> DonePromise, Context Ctx) -> void {
557 auto Guard = onScopeExit([&]() { DonePromise.set_value(std::move(Ctx)); });
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000558
559 auto CurrentVersion = DraftMgr.getVersion(FileStr);
560 if (CurrentVersion != Version)
561 return; // This request is outdated
562
Ilya Biryukov940901e2017-12-13 12:51:22 +0000563 auto Diags = DeferredRebuild(Ctx);
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000564 if (!Diags)
565 return; // A new reparse was requested before this one completed.
Ilya Biryukov47f22022017-09-20 12:58:55 +0000566
567 // We need to serialize access to resulting diagnostics to avoid calling
568 // `onDiagnosticsReady` in the wrong order.
569 std::lock_guard<std::mutex> DiagsLock(DiagnosticsMutex);
570 DocVersion &LastReportedDiagsVersion = ReportedDiagnosticVersions[FileStr];
571 // FIXME(ibiryukov): get rid of '<' comparison here. In the current
572 // implementation diagnostics will not be reported after version counters'
573 // overflow. This should not happen in practice, since DocVersion is a
574 // 64-bit unsigned integer.
575 if (Version < LastReportedDiagsVersion)
576 return;
577 LastReportedDiagsVersion = Version;
578
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000579 DiagConsumer.onDiagnosticsReady(FileStr,
580 make_tagged(std::move(*Diags), Tag));
581 };
582
583 WorkScheduler.addToFront(std::move(ReparseAndPublishDiags),
Ilya Biryukov940901e2017-12-13 12:51:22 +0000584 std::move(DeferredRebuild), std::move(DonePromise),
585 std::move(Ctx));
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000586 return DoneFuture;
587}
588
Ilya Biryukov940901e2017-12-13 12:51:22 +0000589std::future<Context>
590ClangdServer::scheduleCancelRebuild(Context Ctx,
591 std::shared_ptr<CppFile> Resources) {
592 std::promise<Context> DonePromise;
593 std::future<Context> DoneFuture = DonePromise.get_future();
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000594 if (!Resources) {
595 // No need to schedule any cleanup.
Ilya Biryukov940901e2017-12-13 12:51:22 +0000596 DonePromise.set_value(std::move(Ctx));
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000597 return DoneFuture;
598 }
599
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000600 UniqueFunction<void()> DeferredCancel = Resources->deferCancelRebuild();
Ilya Biryukov940901e2017-12-13 12:51:22 +0000601 auto CancelReparses = [Resources](std::promise<Context> DonePromise,
602 UniqueFunction<void()> DeferredCancel,
603 Context Ctx) {
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000604 DeferredCancel();
Ilya Biryukov940901e2017-12-13 12:51:22 +0000605 DonePromise.set_value(std::move(Ctx));
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000606 };
607 WorkScheduler.addToFront(std::move(CancelReparses), std::move(DonePromise),
Ilya Biryukov940901e2017-12-13 12:51:22 +0000608 std::move(DeferredCancel), std::move(Ctx));
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000609 return DoneFuture;
610}
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000611
612void ClangdServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
613 // FIXME: Do nothing for now. This will be used for indexing and potentially
614 // invalidating other caches.
615}