blob: 7cfed091a95333d6b8ad481a4310403bab07b1ee [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,
Haojian Wuba28e9a2018-01-10 14:44:34 +0000137 bool BuildDynamicSymbolIndex, SymbolIndex *StaticIdx,
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),
Haojian Wuba28e9a2018-01-10 14:44:34 +0000141 StaticIdx(StaticIdx),
Eric Liubfac8f72017-12-19 18:00:37 +0000142 // Pass a callback into `Units` to extract symbols from a newly parsed
143 // file and rebuild the file index synchronously each time an AST is
144 // parsed.
145 // FIXME(ioeric): this can be slow and we may be able to index on less
146 // critical paths.
147 Units(FileIdx
148 ? [this](const Context &Ctx, PathRef Path,
149 ParsedAST *AST) { FileIdx->update(Ctx, Path, AST); }
150 : ASTParsedCallback()),
Ilya Biryukova46f7a92017-06-28 10:34:50 +0000151 ResourceDir(ResourceDir ? ResourceDir->str() : getStandardResourceDir()),
Ilya Biryukov38d79772017-05-16 09:38:59 +0000152 PCHs(std::make_shared<PCHContainerOperations>()),
Ilya Biryukove9eb7f02017-11-16 16:25:18 +0000153 StorePreamblesInMemory(StorePreamblesInMemory),
Ilya Biryukovd3b04e32017-12-05 10:42:57 +0000154 WorkScheduler(AsyncThreadsCount) {}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000155
Marc-Andre Laperle37de9712017-09-27 15:31:17 +0000156void ClangdServer::setRootPath(PathRef RootPath) {
157 std::string NewRootPath = llvm::sys::path::convert_to_slash(
158 RootPath, llvm::sys::path::Style::posix);
159 if (llvm::sys::fs::is_directory(NewRootPath))
160 this->RootPath = NewRootPath;
161}
162
Ilya Biryukov940901e2017-12-13 12:51:22 +0000163std::future<Context> ClangdServer::addDocument(Context Ctx, PathRef File,
164 StringRef Contents) {
Ilya Biryukovf01af682017-05-23 13:42:59 +0000165 DocVersion Version = DraftMgr.updateDraft(File, Contents);
Ilya Biryukovf01af682017-05-23 13:42:59 +0000166
Ilya Biryukov02d58702017-08-01 15:51:38 +0000167 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
Ilya Biryukove9eb7f02017-11-16 16:25:18 +0000168 std::shared_ptr<CppFile> Resources = Units.getOrCreateFile(
Ilya Biryukov940901e2017-12-13 12:51:22 +0000169 File, ResourceDir, CDB, StorePreamblesInMemory, PCHs);
170 return scheduleReparseAndDiags(std::move(Ctx), File,
171 VersionedDraft{Version, Contents.str()},
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000172 std::move(Resources), std::move(TaggedFS));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000173}
174
Ilya Biryukov940901e2017-12-13 12:51:22 +0000175std::future<Context> ClangdServer::removeDocument(Context Ctx, PathRef File) {
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000176 DraftMgr.removeDraft(File);
177 std::shared_ptr<CppFile> Resources = Units.removeIfPresent(File);
Ilya Biryukov940901e2017-12-13 12:51:22 +0000178 return scheduleCancelRebuild(std::move(Ctx), std::move(Resources));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000179}
180
Ilya Biryukov940901e2017-12-13 12:51:22 +0000181std::future<Context> ClangdServer::forceReparse(Context Ctx, PathRef File) {
Ilya Biryukov91dbf5b2017-08-14 08:37:32 +0000182 auto FileContents = DraftMgr.getDraft(File);
183 assert(FileContents.Draft &&
184 "forceReparse() was called for non-added document");
185
186 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
Ilya Biryukove9eb7f02017-11-16 16:25:18 +0000187 auto Recreated = Units.recreateFileIfCompileCommandChanged(
Ilya Biryukov940901e2017-12-13 12:51:22 +0000188 File, ResourceDir, CDB, StorePreamblesInMemory, PCHs);
Ilya Biryukov91dbf5b2017-08-14 08:37:32 +0000189
190 // Note that std::future from this cleanup action is ignored.
Ilya Biryukov940901e2017-12-13 12:51:22 +0000191 scheduleCancelRebuild(Ctx.clone(), std::move(Recreated.RemovedFile));
Ilya Biryukov91dbf5b2017-08-14 08:37:32 +0000192 // Schedule a reparse.
Ilya Biryukov940901e2017-12-13 12:51:22 +0000193 return scheduleReparseAndDiags(std::move(Ctx), File, std::move(FileContents),
Ilya Biryukov91dbf5b2017-08-14 08:37:32 +0000194 std::move(Recreated.FileInCollection),
195 std::move(TaggedFS));
Ilya Biryukov0f62ed22017-05-26 12:26:51 +0000196}
197
Ilya Biryukov940901e2017-12-13 12:51:22 +0000198std::future<std::pair<Context, Tagged<CompletionList>>>
199ClangdServer::codeComplete(Context Ctx, PathRef File, Position Pos,
Ilya Biryukovd3b04e32017-12-05 10:42:57 +0000200 const clangd::CodeCompleteOptions &Opts,
Ilya Biryukoved99e4c2017-07-31 17:09:29 +0000201 llvm::Optional<StringRef> OverridenContents,
202 IntrusiveRefCntPtr<vfs::FileSystem> *UsedFS) {
Ilya Biryukov940901e2017-12-13 12:51:22 +0000203 using ResultType = std::pair<Context, Tagged<CompletionList>>;
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000204
205 std::promise<ResultType> ResultPromise;
206
Ilya Biryukov940901e2017-12-13 12:51:22 +0000207 auto Callback = [](std::promise<ResultType> ResultPromise, Context Ctx,
208 Tagged<CompletionList> Result) -> void {
209 ResultPromise.set_value({std::move(Ctx), std::move(Result)});
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000210 };
211
212 std::future<ResultType> ResultFuture = ResultPromise.get_future();
Ilya Biryukov940901e2017-12-13 12:51:22 +0000213 codeComplete(std::move(Ctx), File, Pos, Opts,
214 BindWithForward(Callback, std::move(ResultPromise)),
215 OverridenContents, UsedFS);
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000216 return ResultFuture;
217}
218
219void ClangdServer::codeComplete(
Ilya Biryukov940901e2017-12-13 12:51:22 +0000220 Context Ctx, PathRef File, Position Pos,
221 const clangd::CodeCompleteOptions &Opts,
222 UniqueFunction<void(Context, Tagged<CompletionList>)> Callback,
Ilya Biryukovd3b04e32017-12-05 10:42:57 +0000223 llvm::Optional<StringRef> OverridenContents,
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000224 IntrusiveRefCntPtr<vfs::FileSystem> *UsedFS) {
Ilya Biryukov940901e2017-12-13 12:51:22 +0000225 using CallbackType = UniqueFunction<void(Context, Tagged<CompletionList>)>;
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000226
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000227 std::string Contents;
228 if (OverridenContents) {
229 Contents = *OverridenContents;
230 } else {
Ilya Biryukov0e27ce42017-06-13 14:15:56 +0000231 auto FileContents = DraftMgr.getDraft(File);
232 assert(FileContents.Draft &&
233 "codeComplete is called for non-added document");
234
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000235 Contents = std::move(*FileContents.Draft);
Ilya Biryukov0e27ce42017-06-13 14:15:56 +0000236 }
Ilya Biryukov38d79772017-05-16 09:38:59 +0000237
Ilya Biryukovaf0c04b2017-06-14 09:46:44 +0000238 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
Ilya Biryukoved99e4c2017-07-31 17:09:29 +0000239 if (UsedFS)
240 *UsedFS = TaggedFS.Value;
241
Ilya Biryukov02d58702017-08-01 15:51:38 +0000242 std::shared_ptr<CppFile> Resources = Units.getFile(File);
243 assert(Resources && "Calling completion on non-added file");
244
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000245 // Remember the current Preamble and use it when async task starts executing.
246 // At the point when async task starts executing, we may have a different
247 // Preamble in Resources. However, we assume the Preamble that we obtain here
248 // is reusable in completion more often.
249 std::shared_ptr<const PreambleData> Preamble =
250 Resources->getPossiblyStalePreamble();
Ilya Biryukovd3b04e32017-12-05 10:42:57 +0000251 // Copy completion options for passing them to async task handler.
252 auto CodeCompleteOpts = Opts;
Eric Liubfac8f72017-12-19 18:00:37 +0000253 if (FileIdx)
254 CodeCompleteOpts.Index = FileIdx.get();
Haojian Wuba28e9a2018-01-10 14:44:34 +0000255 if (StaticIdx)
256 CodeCompleteOpts.StaticIndex = StaticIdx;
Ilya Biryukovf6e2b4c2018-01-09 14:39:27 +0000257
258 // Copy File, as it is a PathRef that will go out of scope before Task is
259 // executed.
260 Path FileStr = File;
261 // Copy PCHs to avoid accessing this->PCHs concurrently
262 std::shared_ptr<PCHContainerOperations> PCHs = this->PCHs;
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000263 // A task that will be run asynchronously.
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000264 auto Task =
265 // 'mutable' to reassign Preamble variable.
Ilya Biryukovf6e2b4c2018-01-09 14:39:27 +0000266 [FileStr, Preamble, Resources, Contents, Pos, CodeCompleteOpts, TaggedFS,
267 PCHs](Context Ctx, CallbackType Callback) mutable {
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000268 if (!Preamble) {
269 // Maybe we built some preamble before processing this request.
270 Preamble = Resources->getPossiblyStalePreamble();
271 }
272 // FIXME(ibiryukov): even if Preamble is non-null, we may want to check
273 // both the old and the new version in case only one of them matches.
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000274
Sam McCalla40371b2017-11-15 09:16:29 +0000275 CompletionList Result = clangd::codeComplete(
Ilya Biryukovf6e2b4c2018-01-09 14:39:27 +0000276 Ctx, FileStr, Resources->getCompileCommand(),
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000277 Preamble ? &Preamble->Preamble : nullptr, Contents, Pos,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000278 TaggedFS.Value, PCHs, CodeCompleteOpts);
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000279
Ilya Biryukov940901e2017-12-13 12:51:22 +0000280 Callback(std::move(Ctx),
281 make_tagged(std::move(Result), std::move(TaggedFS.Tag)));
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000282 };
283
Ilya Biryukov940901e2017-12-13 12:51:22 +0000284 WorkScheduler.addToFront(std::move(Task), std::move(Ctx),
285 std::move(Callback));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000286}
Ilya Biryukovf01af682017-05-23 13:42:59 +0000287
Benjamin Krameree19f162017-10-26 12:28:13 +0000288llvm::Expected<Tagged<SignatureHelp>>
Ilya Biryukov940901e2017-12-13 12:51:22 +0000289ClangdServer::signatureHelp(const Context &Ctx, PathRef File, Position Pos,
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000290 llvm::Optional<StringRef> OverridenContents,
291 IntrusiveRefCntPtr<vfs::FileSystem> *UsedFS) {
292 std::string DraftStorage;
293 if (!OverridenContents) {
294 auto FileContents = DraftMgr.getDraft(File);
Benjamin Krameree19f162017-10-26 12:28:13 +0000295 if (!FileContents.Draft)
296 return llvm::make_error<llvm::StringError>(
297 "signatureHelp is called for non-added document",
298 llvm::errc::invalid_argument);
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000299
300 DraftStorage = std::move(*FileContents.Draft);
301 OverridenContents = DraftStorage;
302 }
303
304 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
305 if (UsedFS)
306 *UsedFS = TaggedFS.Value;
307
308 std::shared_ptr<CppFile> Resources = Units.getFile(File);
Benjamin Krameree19f162017-10-26 12:28:13 +0000309 if (!Resources)
310 return llvm::make_error<llvm::StringError>(
311 "signatureHelp is called for non-added document",
312 llvm::errc::invalid_argument);
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000313
314 auto Preamble = Resources->getPossiblyStalePreamble();
Ilya Biryukov940901e2017-12-13 12:51:22 +0000315 auto Result =
316 clangd::signatureHelp(Ctx, File, Resources->getCompileCommand(),
317 Preamble ? &Preamble->Preamble : nullptr,
318 *OverridenContents, Pos, TaggedFS.Value, PCHs);
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000319 return make_tagged(std::move(Result), TaggedFS.Tag);
320}
321
Raoul Wols212bcf82017-12-12 20:25:06 +0000322llvm::Expected<tooling::Replacements>
323ClangdServer::formatRange(StringRef Code, PathRef File, Range Rng) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000324 size_t Begin = positionToOffset(Code, Rng.start);
325 size_t Len = positionToOffset(Code, Rng.end) - Begin;
326 return formatCode(Code, File, {tooling::Range(Begin, Len)});
327}
328
Raoul Wols212bcf82017-12-12 20:25:06 +0000329llvm::Expected<tooling::Replacements> ClangdServer::formatFile(StringRef Code,
330 PathRef File) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000331 // Format everything.
Ilya Biryukovafb55542017-05-16 14:40:30 +0000332 return formatCode(Code, File, {tooling::Range(0, Code.size())});
333}
334
Raoul Wols212bcf82017-12-12 20:25:06 +0000335llvm::Expected<tooling::Replacements>
336ClangdServer::formatOnType(StringRef Code, PathRef File, Position Pos) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000337 // Look for the previous opening brace from the character position and
338 // format starting from there.
Ilya Biryukovafb55542017-05-16 14:40:30 +0000339 size_t CursorPos = positionToOffset(Code, Pos);
340 size_t PreviousLBracePos = StringRef(Code).find_last_of('{', CursorPos);
341 if (PreviousLBracePos == StringRef::npos)
342 PreviousLBracePos = CursorPos;
Sam McCallb536a2a2017-12-19 12:23:48 +0000343 size_t Len = CursorPos - PreviousLBracePos;
Ilya Biryukovafb55542017-05-16 14:40:30 +0000344
345 return formatCode(Code, File, {tooling::Range(PreviousLBracePos, Len)});
346}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000347
Haojian Wu345099c2017-11-09 11:30:04 +0000348Expected<std::vector<tooling::Replacement>>
Ilya Biryukov940901e2017-12-13 12:51:22 +0000349ClangdServer::rename(const Context &Ctx, PathRef File, Position Pos,
350 llvm::StringRef NewName) {
Haojian Wu345099c2017-11-09 11:30:04 +0000351 std::string Code = getDocument(File);
352 std::shared_ptr<CppFile> Resources = Units.getFile(File);
353 RefactoringResultCollector ResultCollector;
354 Resources->getAST().get()->runUnderLock([&](ParsedAST *AST) {
355 const SourceManager &SourceMgr = AST->getASTContext().getSourceManager();
356 const FileEntry *FE =
357 SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
358 if (!FE)
359 return;
360 SourceLocation SourceLocationBeg =
361 clangd::getBeginningOfIdentifier(*AST, Pos, FE);
362 tooling::RefactoringRuleContext Context(
363 AST->getASTContext().getSourceManager());
364 Context.setASTContext(AST->getASTContext());
365 auto Rename = clang::tooling::RenameOccurrences::initiate(
366 Context, SourceRange(SourceLocationBeg), NewName.str());
367 if (!Rename) {
368 ResultCollector.Result = Rename.takeError();
369 return;
370 }
371 Rename->invoke(ResultCollector, Context);
372 });
373 assert(ResultCollector.Result.hasValue());
374 if (!ResultCollector.Result.getValue())
375 return ResultCollector.Result->takeError();
376
377 std::vector<tooling::Replacement> Replacements;
378 for (const tooling::AtomicChange &Change : ResultCollector.Result->get()) {
379 tooling::Replacements ChangeReps = Change.getReplacements();
380 for (const auto &Rep : ChangeReps) {
381 // FIXME: Right now we only support renaming the main file, so we drop
382 // replacements not for the main file. In the future, we might consider to
383 // support:
384 // * rename in any included header
385 // * rename only in the "main" header
386 // * provide an error if there are symbols we won't rename (e.g.
387 // std::vector)
388 // * rename globally in project
389 // * rename in open files
390 if (Rep.getFilePath() == File)
391 Replacements.push_back(Rep);
392 }
393 }
394 return Replacements;
395}
396
Ilya Biryukov38d79772017-05-16 09:38:59 +0000397std::string ClangdServer::getDocument(PathRef File) {
398 auto draft = DraftMgr.getDraft(File);
399 assert(draft.Draft && "File is not tracked, cannot get contents");
400 return *draft.Draft;
401}
402
Ilya Biryukovf01af682017-05-23 13:42:59 +0000403std::string ClangdServer::dumpAST(PathRef File) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000404 std::shared_ptr<CppFile> Resources = Units.getFile(File);
405 assert(Resources && "dumpAST is called for non-added document");
Ilya Biryukov38d79772017-05-16 09:38:59 +0000406
Ilya Biryukov02d58702017-08-01 15:51:38 +0000407 std::string Result;
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +0000408 Resources->getAST().get()->runUnderLock([&Result](ParsedAST *AST) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000409 llvm::raw_string_ostream ResultOS(Result);
410 if (AST) {
411 clangd::dumpAST(*AST, ResultOS);
412 } else {
413 ResultOS << "<no-ast>";
414 }
415 ResultOS.flush();
Ilya Biryukovf01af682017-05-23 13:42:59 +0000416 });
Ilya Biryukov02d58702017-08-01 15:51:38 +0000417 return Result;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000418}
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000419
Benjamin Krameree19f162017-10-26 12:28:13 +0000420llvm::Expected<Tagged<std::vector<Location>>>
Ilya Biryukov940901e2017-12-13 12:51:22 +0000421ClangdServer::findDefinitions(const Context &Ctx, PathRef File, Position Pos) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000422 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
423
424 std::shared_ptr<CppFile> Resources = Units.getFile(File);
Benjamin Krameree19f162017-10-26 12:28:13 +0000425 if (!Resources)
426 return llvm::make_error<llvm::StringError>(
427 "findDefinitions called on non-added file",
428 llvm::errc::invalid_argument);
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000429
430 std::vector<Location> Result;
Ilya Biryukov940901e2017-12-13 12:51:22 +0000431 Resources->getAST().get()->runUnderLock([Pos, &Result, &Ctx](ParsedAST *AST) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000432 if (!AST)
433 return;
Ilya Biryukov940901e2017-12-13 12:51:22 +0000434 Result = clangd::findDefinitions(Ctx, *AST, Pos);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000435 });
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000436 return make_tagged(std::move(Result), TaggedFS.Tag);
437}
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000438
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000439llvm::Optional<Path> ClangdServer::switchSourceHeader(PathRef Path) {
440
441 StringRef SourceExtensions[] = {".cpp", ".c", ".cc", ".cxx",
442 ".c++", ".m", ".mm"};
443 StringRef HeaderExtensions[] = {".h", ".hh", ".hpp", ".hxx", ".inc"};
444
445 StringRef PathExt = llvm::sys::path::extension(Path);
446
447 // Lookup in a list of known extensions.
448 auto SourceIter =
449 std::find_if(std::begin(SourceExtensions), std::end(SourceExtensions),
450 [&PathExt](PathRef SourceExt) {
451 return SourceExt.equals_lower(PathExt);
452 });
453 bool IsSource = SourceIter != std::end(SourceExtensions);
454
455 auto HeaderIter =
456 std::find_if(std::begin(HeaderExtensions), std::end(HeaderExtensions),
457 [&PathExt](PathRef HeaderExt) {
458 return HeaderExt.equals_lower(PathExt);
459 });
460
461 bool IsHeader = HeaderIter != std::end(HeaderExtensions);
462
463 // We can only switch between extensions known extensions.
464 if (!IsSource && !IsHeader)
465 return llvm::None;
466
467 // Array to lookup extensions for the switch. An opposite of where original
468 // extension was found.
469 ArrayRef<StringRef> NewExts;
470 if (IsSource)
471 NewExts = HeaderExtensions;
472 else
473 NewExts = SourceExtensions;
474
475 // Storage for the new path.
476 SmallString<128> NewPath = StringRef(Path);
477
478 // Instance of vfs::FileSystem, used for file existence checks.
479 auto FS = FSProvider.getTaggedFileSystem(Path).Value;
480
481 // Loop through switched extension candidates.
482 for (StringRef NewExt : NewExts) {
483 llvm::sys::path::replace_extension(NewPath, NewExt);
484 if (FS->exists(NewPath))
485 return NewPath.str().str(); // First str() to convert from SmallString to
486 // StringRef, second to convert from StringRef
487 // to std::string
Ilya Biryukov33334942017-10-06 14:39:39 +0000488
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000489 // Also check NewExt in upper-case, just in case.
490 llvm::sys::path::replace_extension(NewPath, NewExt.upper());
491 if (FS->exists(NewPath))
492 return NewPath.str().str();
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000493 }
494
495 return llvm::None;
496}
497
Raoul Wols212bcf82017-12-12 20:25:06 +0000498llvm::Expected<tooling::Replacements>
499ClangdServer::formatCode(llvm::StringRef Code, PathRef File,
500 ArrayRef<tooling::Range> Ranges) {
501 // Call clang-format.
502 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
503 auto StyleOrError =
504 format::getStyle("file", File, "LLVM", Code, TaggedFS.Value.get());
505 if (!StyleOrError) {
506 return StyleOrError.takeError();
507 } else {
508 return format::reformat(StyleOrError.get(), Code, Ranges, File);
509 }
510}
511
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000512llvm::Expected<Tagged<std::vector<DocumentHighlight>>>
Ilya Biryukov940901e2017-12-13 12:51:22 +0000513ClangdServer::findDocumentHighlights(const Context &Ctx, PathRef File,
514 Position Pos) {
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000515 auto FileContents = DraftMgr.getDraft(File);
516 if (!FileContents.Draft)
517 return llvm::make_error<llvm::StringError>(
518 "findDocumentHighlights called on non-added file",
519 llvm::errc::invalid_argument);
520
521 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
522
523 std::shared_ptr<CppFile> Resources = Units.getFile(File);
524 if (!Resources)
525 return llvm::make_error<llvm::StringError>(
526 "findDocumentHighlights called on non-added file",
527 llvm::errc::invalid_argument);
528
529 std::vector<DocumentHighlight> Result;
530 llvm::Optional<llvm::Error> Err;
Ilya Biryukov940901e2017-12-13 12:51:22 +0000531 Resources->getAST().get()->runUnderLock([Pos, &Ctx, &Err,
532 &Result](ParsedAST *AST) {
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000533 if (!AST) {
534 Err = llvm::make_error<llvm::StringError>("Invalid AST",
535 llvm::errc::invalid_argument);
536 return;
537 }
Ilya Biryukov940901e2017-12-13 12:51:22 +0000538 Result = clangd::findDocumentHighlights(Ctx, *AST, Pos);
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000539 });
540
541 if (Err)
542 return std::move(*Err);
543 return make_tagged(Result, TaggedFS.Tag);
544}
545
Ilya Biryukov940901e2017-12-13 12:51:22 +0000546std::future<Context> ClangdServer::scheduleReparseAndDiags(
547 Context Ctx, PathRef File, VersionedDraft Contents,
548 std::shared_ptr<CppFile> Resources,
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000549 Tagged<IntrusiveRefCntPtr<vfs::FileSystem>> TaggedFS) {
550
551 assert(Contents.Draft && "Draft must have contents");
Ilya Biryukov940901e2017-12-13 12:51:22 +0000552 UniqueFunction<llvm::Optional<std::vector<DiagWithFixIts>>(const Context &)>
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000553 DeferredRebuild =
554 Resources->deferRebuild(*Contents.Draft, TaggedFS.Value);
Ilya Biryukov940901e2017-12-13 12:51:22 +0000555 std::promise<Context> DonePromise;
556 std::future<Context> DoneFuture = DonePromise.get_future();
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000557
558 DocVersion Version = Contents.Version;
559 Path FileStr = File;
560 VFSTag Tag = TaggedFS.Tag;
561 auto ReparseAndPublishDiags =
562 [this, FileStr, Version,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000563 Tag](UniqueFunction<llvm::Optional<std::vector<DiagWithFixIts>>(
564 const Context &)>
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000565 DeferredRebuild,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000566 std::promise<Context> DonePromise, Context Ctx) -> void {
567 auto Guard = onScopeExit([&]() { DonePromise.set_value(std::move(Ctx)); });
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000568
569 auto CurrentVersion = DraftMgr.getVersion(FileStr);
570 if (CurrentVersion != Version)
571 return; // This request is outdated
572
Ilya Biryukov940901e2017-12-13 12:51:22 +0000573 auto Diags = DeferredRebuild(Ctx);
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000574 if (!Diags)
575 return; // A new reparse was requested before this one completed.
Ilya Biryukov47f22022017-09-20 12:58:55 +0000576
577 // We need to serialize access to resulting diagnostics to avoid calling
578 // `onDiagnosticsReady` in the wrong order.
579 std::lock_guard<std::mutex> DiagsLock(DiagnosticsMutex);
580 DocVersion &LastReportedDiagsVersion = ReportedDiagnosticVersions[FileStr];
581 // FIXME(ibiryukov): get rid of '<' comparison here. In the current
582 // implementation diagnostics will not be reported after version counters'
583 // overflow. This should not happen in practice, since DocVersion is a
584 // 64-bit unsigned integer.
585 if (Version < LastReportedDiagsVersion)
586 return;
587 LastReportedDiagsVersion = Version;
588
Ilya Biryukov95558392018-01-10 17:59:27 +0000589 DiagConsumer.onDiagnosticsReady(Ctx, FileStr,
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000590 make_tagged(std::move(*Diags), Tag));
591 };
592
593 WorkScheduler.addToFront(std::move(ReparseAndPublishDiags),
Ilya Biryukov940901e2017-12-13 12:51:22 +0000594 std::move(DeferredRebuild), std::move(DonePromise),
595 std::move(Ctx));
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000596 return DoneFuture;
597}
598
Ilya Biryukov940901e2017-12-13 12:51:22 +0000599std::future<Context>
600ClangdServer::scheduleCancelRebuild(Context Ctx,
601 std::shared_ptr<CppFile> Resources) {
602 std::promise<Context> DonePromise;
603 std::future<Context> DoneFuture = DonePromise.get_future();
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000604 if (!Resources) {
605 // No need to schedule any cleanup.
Ilya Biryukov940901e2017-12-13 12:51:22 +0000606 DonePromise.set_value(std::move(Ctx));
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000607 return DoneFuture;
608 }
609
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000610 UniqueFunction<void()> DeferredCancel = Resources->deferCancelRebuild();
Ilya Biryukov940901e2017-12-13 12:51:22 +0000611 auto CancelReparses = [Resources](std::promise<Context> DonePromise,
612 UniqueFunction<void()> DeferredCancel,
613 Context Ctx) {
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000614 DeferredCancel();
Ilya Biryukov940901e2017-12-13 12:51:22 +0000615 DonePromise.set_value(std::move(Ctx));
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000616 };
617 WorkScheduler.addToFront(std::move(CancelReparses), std::move(DonePromise),
Ilya Biryukov940901e2017-12-13 12:51:22 +0000618 std::move(DeferredCancel), std::move(Ctx));
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000619 return DoneFuture;
620}
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000621
622void ClangdServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
623 // FIXME: Do nothing for now. This will be used for indexing and potentially
624 // invalidating other caches.
625}