blob: 883ca35764cabe46a33f3cad6eb8fdd509393b7b [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 Biryukovf6e2b4c2018-01-09 14:39:27 +0000254
255 // Copy File, as it is a PathRef that will go out of scope before Task is
256 // executed.
257 Path FileStr = File;
258 // Copy PCHs to avoid accessing this->PCHs concurrently
259 std::shared_ptr<PCHContainerOperations> PCHs = this->PCHs;
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000260 // A task that will be run asynchronously.
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000261 auto Task =
262 // 'mutable' to reassign Preamble variable.
Ilya Biryukovf6e2b4c2018-01-09 14:39:27 +0000263 [FileStr, Preamble, Resources, Contents, Pos, CodeCompleteOpts, TaggedFS,
264 PCHs](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 Biryukovf6e2b4c2018-01-09 14:39:27 +0000273 Ctx, FileStr, 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;
Sam McCallb536a2a2017-12-19 12:23:48 +0000340 size_t Len = CursorPos - PreviousLBracePos;
Ilya Biryukovafb55542017-05-16 14:40:30 +0000341
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}