blob: 21ed7576963aa3b3ba4ffa413258e15516d74a47 [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"
Sam McCall0faecf02018-01-15 12:33:00 +000014#include "index/Merge.h"
Ilya Biryukovafb55542017-05-16 14:40:30 +000015#include "clang/Format/Format.h"
Ilya Biryukov38d79772017-05-16 09:38:59 +000016#include "clang/Frontend/CompilerInstance.h"
17#include "clang/Frontend/CompilerInvocation.h"
18#include "clang/Tooling/CompilationDatabase.h"
Ilya Biryukov9e11c4c2017-11-15 18:04:56 +000019#include "clang/Tooling/Refactoring/RefactoringResultConsumer.h"
20#include "clang/Tooling/Refactoring/Rename/RenamingAction.h"
Ilya Biryukovafb55542017-05-16 14:40:30 +000021#include "llvm/ADT/ArrayRef.h"
Benjamin Krameree19f162017-10-26 12:28:13 +000022#include "llvm/Support/Errc.h"
Ilya Biryukov38d79772017-05-16 09:38:59 +000023#include "llvm/Support/FileSystem.h"
Sam McCall8567cb32017-11-02 09:21:51 +000024#include "llvm/Support/FormatProviders.h"
25#include "llvm/Support/FormatVariadic.h"
Marc-Andre Laperle37de9712017-09-27 15:31:17 +000026#include "llvm/Support/Path.h"
Ilya Biryukovf01af682017-05-23 13:42:59 +000027#include "llvm/Support/raw_ostream.h"
28#include <future>
Ilya Biryukov38d79772017-05-16 09:38:59 +000029
Ilya Biryukov2f314102017-05-16 10:06:20 +000030using namespace clang;
Ilya Biryukov38d79772017-05-16 09:38:59 +000031using namespace clang::clangd;
32
Ilya Biryukovafb55542017-05-16 14:40:30 +000033namespace {
34
Ilya Biryukova46f7a92017-06-28 10:34:50 +000035std::string getStandardResourceDir() {
36 static int Dummy; // Just an address in this process.
37 return CompilerInvocation::GetResourcesPath("clangd", (void *)&Dummy);
38}
39
Haojian Wu345099c2017-11-09 11:30:04 +000040class RefactoringResultCollector final
41 : public tooling::RefactoringResultConsumer {
42public:
43 void handleError(llvm::Error Err) override {
44 assert(!Result.hasValue());
45 // FIXME: figure out a way to return better message for DiagnosticError.
46 // clangd uses llvm::toString to convert the Err to string, however, for
47 // DiagnosticError, only "clang diagnostic" will be generated.
48 Result = std::move(Err);
49 }
50
51 // Using the handle(SymbolOccurrences) from parent class.
52 using tooling::RefactoringResultConsumer::handle;
53
54 void handle(tooling::AtomicChanges SourceReplacements) override {
55 assert(!Result.hasValue());
56 Result = std::move(SourceReplacements);
57 }
58
59 Optional<Expected<tooling::AtomicChanges>> Result;
60};
61
Ilya Biryukovafb55542017-05-16 14:40:30 +000062} // namespace
63
Ilya Biryukov22602992017-05-30 15:11:02 +000064Tagged<IntrusiveRefCntPtr<vfs::FileSystem>>
Ilya Biryukovaf0c04b2017-06-14 09:46:44 +000065RealFileSystemProvider::getTaggedFileSystem(PathRef File) {
Ilya Biryukov22602992017-05-30 15:11:02 +000066 return make_tagged(vfs::getRealFileSystem(), VFSTag());
Ilya Biryukov0f62ed22017-05-26 12:26:51 +000067}
68
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +000069unsigned clangd::getDefaultAsyncThreadsCount() {
70 unsigned HardwareConcurrency = std::thread::hardware_concurrency();
71 // C++ standard says that hardware_concurrency()
72 // may return 0, fallback to 1 worker thread in
73 // that case.
74 if (HardwareConcurrency == 0)
75 return 1;
76 return HardwareConcurrency;
77}
78
79ClangdScheduler::ClangdScheduler(unsigned AsyncThreadsCount)
80 : RunSynchronously(AsyncThreadsCount == 0) {
Ilya Biryukov38d79772017-05-16 09:38:59 +000081 if (RunSynchronously) {
82 // Don't start the worker thread if we're running synchronously
83 return;
84 }
85
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +000086 Workers.reserve(AsyncThreadsCount);
87 for (unsigned I = 0; I < AsyncThreadsCount; ++I) {
Sam McCall8567cb32017-11-02 09:21:51 +000088 Workers.push_back(std::thread([this, I]() {
89 llvm::set_thread_name(llvm::formatv("scheduler/{0}", I));
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +000090 while (true) {
Ilya Biryukov08e6ccb2017-10-09 16:26:26 +000091 UniqueFunction<void()> Request;
Ilya Biryukov38d79772017-05-16 09:38:59 +000092
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +000093 // Pick request from the queue
94 {
95 std::unique_lock<std::mutex> Lock(Mutex);
96 // Wait for more requests.
97 RequestCV.wait(Lock,
98 [this] { return !RequestQueue.empty() || Done; });
99 if (Done)
100 return;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000101
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000102 assert(!RequestQueue.empty() && "RequestQueue was empty");
Ilya Biryukov38d79772017-05-16 09:38:59 +0000103
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000104 // We process requests starting from the front of the queue. Users of
105 // ClangdScheduler have a way to prioritise their requests by putting
106 // them to the either side of the queue (using either addToEnd or
107 // addToFront).
108 Request = std::move(RequestQueue.front());
109 RequestQueue.pop_front();
110 } // unlock Mutex
Ilya Biryukov38d79772017-05-16 09:38:59 +0000111
Ilya Biryukov08e6ccb2017-10-09 16:26:26 +0000112 Request();
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000113 }
114 }));
115 }
Ilya Biryukov38d79772017-05-16 09:38:59 +0000116}
117
118ClangdScheduler::~ClangdScheduler() {
119 if (RunSynchronously)
120 return; // no worker thread is running in that case
121
122 {
123 std::lock_guard<std::mutex> Lock(Mutex);
124 // Wake up the worker thread
125 Done = true;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000126 } // unlock Mutex
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000127 RequestCV.notify_all();
128
129 for (auto &Worker : Workers)
130 Worker.join();
Ilya Biryukov38d79772017-05-16 09:38:59 +0000131}
132
Sam McCalladccab62017-11-23 16:58:22 +0000133ClangdServer::ClangdServer(GlobalCompilationDatabase &CDB,
134 DiagnosticsConsumer &DiagConsumer,
135 FileSystemProvider &FSProvider,
136 unsigned AsyncThreadsCount,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000137 bool StorePreamblesInMemory,
Haojian Wuba28e9a2018-01-10 14:44:34 +0000138 bool BuildDynamicSymbolIndex, SymbolIndex *StaticIdx,
Sam McCalladccab62017-11-23 16:58:22 +0000139 llvm::Optional<StringRef> ResourceDir)
Ilya Biryukov940901e2017-12-13 12:51:22 +0000140 : CDB(CDB), DiagConsumer(DiagConsumer), FSProvider(FSProvider),
Eric Liubfac8f72017-12-19 18:00:37 +0000141 FileIdx(BuildDynamicSymbolIndex ? new FileIndex() : nullptr),
142 // 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),
Sam McCall0faecf02018-01-15 12:33:00 +0000154 WorkScheduler(AsyncThreadsCount) {
155 if (FileIdx && StaticIdx) {
156 MergedIndex = mergeIndex(FileIdx.get(), StaticIdx);
157 Index = MergedIndex.get();
158 } else if (FileIdx)
159 Index = FileIdx.get();
160 else if (StaticIdx)
161 Index = StaticIdx;
162 else
163 Index = nullptr;
164}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000165
Marc-Andre Laperle37de9712017-09-27 15:31:17 +0000166void ClangdServer::setRootPath(PathRef RootPath) {
167 std::string NewRootPath = llvm::sys::path::convert_to_slash(
168 RootPath, llvm::sys::path::Style::posix);
169 if (llvm::sys::fs::is_directory(NewRootPath))
170 this->RootPath = NewRootPath;
171}
172
Ilya Biryukov940901e2017-12-13 12:51:22 +0000173std::future<Context> ClangdServer::addDocument(Context Ctx, PathRef File,
174 StringRef Contents) {
Ilya Biryukovf01af682017-05-23 13:42:59 +0000175 DocVersion Version = DraftMgr.updateDraft(File, Contents);
Ilya Biryukovf01af682017-05-23 13:42:59 +0000176
Ilya Biryukov02d58702017-08-01 15:51:38 +0000177 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
Ilya Biryukove9eb7f02017-11-16 16:25:18 +0000178 std::shared_ptr<CppFile> Resources = Units.getOrCreateFile(
Ilya Biryukov940901e2017-12-13 12:51:22 +0000179 File, ResourceDir, CDB, StorePreamblesInMemory, PCHs);
180 return scheduleReparseAndDiags(std::move(Ctx), File,
181 VersionedDraft{Version, Contents.str()},
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000182 std::move(Resources), std::move(TaggedFS));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000183}
184
Ilya Biryukov940901e2017-12-13 12:51:22 +0000185std::future<Context> ClangdServer::removeDocument(Context Ctx, PathRef File) {
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000186 DraftMgr.removeDraft(File);
187 std::shared_ptr<CppFile> Resources = Units.removeIfPresent(File);
Ilya Biryukov940901e2017-12-13 12:51:22 +0000188 return scheduleCancelRebuild(std::move(Ctx), std::move(Resources));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000189}
190
Ilya Biryukov940901e2017-12-13 12:51:22 +0000191std::future<Context> ClangdServer::forceReparse(Context Ctx, PathRef File) {
Ilya Biryukov91dbf5b2017-08-14 08:37:32 +0000192 auto FileContents = DraftMgr.getDraft(File);
193 assert(FileContents.Draft &&
194 "forceReparse() was called for non-added document");
195
196 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
Ilya Biryukove9eb7f02017-11-16 16:25:18 +0000197 auto Recreated = Units.recreateFileIfCompileCommandChanged(
Ilya Biryukov940901e2017-12-13 12:51:22 +0000198 File, ResourceDir, CDB, StorePreamblesInMemory, PCHs);
Ilya Biryukov91dbf5b2017-08-14 08:37:32 +0000199
200 // Note that std::future from this cleanup action is ignored.
Ilya Biryukov940901e2017-12-13 12:51:22 +0000201 scheduleCancelRebuild(Ctx.clone(), std::move(Recreated.RemovedFile));
Ilya Biryukov91dbf5b2017-08-14 08:37:32 +0000202 // Schedule a reparse.
Ilya Biryukov940901e2017-12-13 12:51:22 +0000203 return scheduleReparseAndDiags(std::move(Ctx), File, std::move(FileContents),
Ilya Biryukov91dbf5b2017-08-14 08:37:32 +0000204 std::move(Recreated.FileInCollection),
205 std::move(TaggedFS));
Ilya Biryukov0f62ed22017-05-26 12:26:51 +0000206}
207
Ilya Biryukov940901e2017-12-13 12:51:22 +0000208std::future<std::pair<Context, Tagged<CompletionList>>>
209ClangdServer::codeComplete(Context Ctx, PathRef File, Position Pos,
Ilya Biryukovd3b04e32017-12-05 10:42:57 +0000210 const clangd::CodeCompleteOptions &Opts,
Ilya Biryukoved99e4c2017-07-31 17:09:29 +0000211 llvm::Optional<StringRef> OverridenContents,
212 IntrusiveRefCntPtr<vfs::FileSystem> *UsedFS) {
Ilya Biryukov940901e2017-12-13 12:51:22 +0000213 using ResultType = std::pair<Context, Tagged<CompletionList>>;
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000214
215 std::promise<ResultType> ResultPromise;
216
Ilya Biryukov940901e2017-12-13 12:51:22 +0000217 auto Callback = [](std::promise<ResultType> ResultPromise, Context Ctx,
218 Tagged<CompletionList> Result) -> void {
219 ResultPromise.set_value({std::move(Ctx), std::move(Result)});
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000220 };
221
222 std::future<ResultType> ResultFuture = ResultPromise.get_future();
Ilya Biryukov940901e2017-12-13 12:51:22 +0000223 codeComplete(std::move(Ctx), File, Pos, Opts,
224 BindWithForward(Callback, std::move(ResultPromise)),
225 OverridenContents, UsedFS);
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000226 return ResultFuture;
227}
228
229void ClangdServer::codeComplete(
Ilya Biryukov940901e2017-12-13 12:51:22 +0000230 Context Ctx, PathRef File, Position Pos,
231 const clangd::CodeCompleteOptions &Opts,
232 UniqueFunction<void(Context, Tagged<CompletionList>)> Callback,
Ilya Biryukovd3b04e32017-12-05 10:42:57 +0000233 llvm::Optional<StringRef> OverridenContents,
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000234 IntrusiveRefCntPtr<vfs::FileSystem> *UsedFS) {
Ilya Biryukov940901e2017-12-13 12:51:22 +0000235 using CallbackType = UniqueFunction<void(Context, Tagged<CompletionList>)>;
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000236
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000237 std::string Contents;
238 if (OverridenContents) {
239 Contents = *OverridenContents;
240 } else {
Ilya Biryukov0e27ce42017-06-13 14:15:56 +0000241 auto FileContents = DraftMgr.getDraft(File);
242 assert(FileContents.Draft &&
243 "codeComplete is called for non-added document");
244
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000245 Contents = std::move(*FileContents.Draft);
Ilya Biryukov0e27ce42017-06-13 14:15:56 +0000246 }
Ilya Biryukov38d79772017-05-16 09:38:59 +0000247
Ilya Biryukovaf0c04b2017-06-14 09:46:44 +0000248 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
Ilya Biryukoved99e4c2017-07-31 17:09:29 +0000249 if (UsedFS)
250 *UsedFS = TaggedFS.Value;
251
Ilya Biryukov02d58702017-08-01 15:51:38 +0000252 std::shared_ptr<CppFile> Resources = Units.getFile(File);
253 assert(Resources && "Calling completion on non-added file");
254
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000255 // Remember the current Preamble and use it when async task starts executing.
256 // At the point when async task starts executing, we may have a different
257 // Preamble in Resources. However, we assume the Preamble that we obtain here
258 // is reusable in completion more often.
259 std::shared_ptr<const PreambleData> Preamble =
260 Resources->getPossiblyStalePreamble();
Ilya Biryukovd3b04e32017-12-05 10:42:57 +0000261 // Copy completion options for passing them to async task handler.
262 auto CodeCompleteOpts = Opts;
Sam McCall0faecf02018-01-15 12:33:00 +0000263 if (!CodeCompleteOpts.Index) // Respect overridden index.
264 CodeCompleteOpts.Index = Index;
Ilya Biryukovf6e2b4c2018-01-09 14:39:27 +0000265
266 // Copy File, as it is a PathRef that will go out of scope before Task is
267 // executed.
268 Path FileStr = File;
269 // Copy PCHs to avoid accessing this->PCHs concurrently
270 std::shared_ptr<PCHContainerOperations> PCHs = this->PCHs;
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000271 // A task that will be run asynchronously.
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000272 auto Task =
273 // 'mutable' to reassign Preamble variable.
Ilya Biryukovf6e2b4c2018-01-09 14:39:27 +0000274 [FileStr, Preamble, Resources, Contents, Pos, CodeCompleteOpts, TaggedFS,
275 PCHs](Context Ctx, CallbackType Callback) mutable {
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000276 if (!Preamble) {
277 // Maybe we built some preamble before processing this request.
278 Preamble = Resources->getPossiblyStalePreamble();
279 }
280 // FIXME(ibiryukov): even if Preamble is non-null, we may want to check
281 // both the old and the new version in case only one of them matches.
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000282
Sam McCalla40371b2017-11-15 09:16:29 +0000283 CompletionList Result = clangd::codeComplete(
Ilya Biryukovf6e2b4c2018-01-09 14:39:27 +0000284 Ctx, FileStr, Resources->getCompileCommand(),
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000285 Preamble ? &Preamble->Preamble : nullptr, Contents, Pos,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000286 TaggedFS.Value, PCHs, CodeCompleteOpts);
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000287
Ilya Biryukov940901e2017-12-13 12:51:22 +0000288 Callback(std::move(Ctx),
289 make_tagged(std::move(Result), std::move(TaggedFS.Tag)));
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000290 };
291
Ilya Biryukov940901e2017-12-13 12:51:22 +0000292 WorkScheduler.addToFront(std::move(Task), std::move(Ctx),
293 std::move(Callback));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000294}
Ilya Biryukovf01af682017-05-23 13:42:59 +0000295
Benjamin Krameree19f162017-10-26 12:28:13 +0000296llvm::Expected<Tagged<SignatureHelp>>
Ilya Biryukov940901e2017-12-13 12:51:22 +0000297ClangdServer::signatureHelp(const Context &Ctx, PathRef File, Position Pos,
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000298 llvm::Optional<StringRef> OverridenContents,
299 IntrusiveRefCntPtr<vfs::FileSystem> *UsedFS) {
300 std::string DraftStorage;
301 if (!OverridenContents) {
302 auto FileContents = DraftMgr.getDraft(File);
Benjamin Krameree19f162017-10-26 12:28:13 +0000303 if (!FileContents.Draft)
304 return llvm::make_error<llvm::StringError>(
305 "signatureHelp is called for non-added document",
306 llvm::errc::invalid_argument);
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000307
308 DraftStorage = std::move(*FileContents.Draft);
309 OverridenContents = DraftStorage;
310 }
311
312 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
313 if (UsedFS)
314 *UsedFS = TaggedFS.Value;
315
316 std::shared_ptr<CppFile> Resources = Units.getFile(File);
Benjamin Krameree19f162017-10-26 12:28:13 +0000317 if (!Resources)
318 return llvm::make_error<llvm::StringError>(
319 "signatureHelp is called for non-added document",
320 llvm::errc::invalid_argument);
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000321
322 auto Preamble = Resources->getPossiblyStalePreamble();
Ilya Biryukov940901e2017-12-13 12:51:22 +0000323 auto Result =
324 clangd::signatureHelp(Ctx, File, Resources->getCompileCommand(),
325 Preamble ? &Preamble->Preamble : nullptr,
326 *OverridenContents, Pos, TaggedFS.Value, PCHs);
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000327 return make_tagged(std::move(Result), TaggedFS.Tag);
328}
329
Raoul Wols212bcf82017-12-12 20:25:06 +0000330llvm::Expected<tooling::Replacements>
331ClangdServer::formatRange(StringRef Code, PathRef File, Range Rng) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000332 size_t Begin = positionToOffset(Code, Rng.start);
333 size_t Len = positionToOffset(Code, Rng.end) - Begin;
334 return formatCode(Code, File, {tooling::Range(Begin, Len)});
335}
336
Raoul Wols212bcf82017-12-12 20:25:06 +0000337llvm::Expected<tooling::Replacements> ClangdServer::formatFile(StringRef Code,
338 PathRef File) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000339 // Format everything.
Ilya Biryukovafb55542017-05-16 14:40:30 +0000340 return formatCode(Code, File, {tooling::Range(0, Code.size())});
341}
342
Raoul Wols212bcf82017-12-12 20:25:06 +0000343llvm::Expected<tooling::Replacements>
344ClangdServer::formatOnType(StringRef Code, PathRef File, Position Pos) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000345 // Look for the previous opening brace from the character position and
346 // format starting from there.
Ilya Biryukovafb55542017-05-16 14:40:30 +0000347 size_t CursorPos = positionToOffset(Code, Pos);
348 size_t PreviousLBracePos = StringRef(Code).find_last_of('{', CursorPos);
349 if (PreviousLBracePos == StringRef::npos)
350 PreviousLBracePos = CursorPos;
Sam McCallb536a2a2017-12-19 12:23:48 +0000351 size_t Len = CursorPos - PreviousLBracePos;
Ilya Biryukovafb55542017-05-16 14:40:30 +0000352
353 return formatCode(Code, File, {tooling::Range(PreviousLBracePos, Len)});
354}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000355
Haojian Wu345099c2017-11-09 11:30:04 +0000356Expected<std::vector<tooling::Replacement>>
Ilya Biryukov940901e2017-12-13 12:51:22 +0000357ClangdServer::rename(const Context &Ctx, PathRef File, Position Pos,
358 llvm::StringRef NewName) {
Haojian Wu345099c2017-11-09 11:30:04 +0000359 std::string Code = getDocument(File);
360 std::shared_ptr<CppFile> Resources = Units.getFile(File);
361 RefactoringResultCollector ResultCollector;
362 Resources->getAST().get()->runUnderLock([&](ParsedAST *AST) {
363 const SourceManager &SourceMgr = AST->getASTContext().getSourceManager();
364 const FileEntry *FE =
365 SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
366 if (!FE)
367 return;
368 SourceLocation SourceLocationBeg =
369 clangd::getBeginningOfIdentifier(*AST, Pos, FE);
370 tooling::RefactoringRuleContext Context(
371 AST->getASTContext().getSourceManager());
372 Context.setASTContext(AST->getASTContext());
373 auto Rename = clang::tooling::RenameOccurrences::initiate(
374 Context, SourceRange(SourceLocationBeg), NewName.str());
375 if (!Rename) {
376 ResultCollector.Result = Rename.takeError();
377 return;
378 }
379 Rename->invoke(ResultCollector, Context);
380 });
381 assert(ResultCollector.Result.hasValue());
382 if (!ResultCollector.Result.getValue())
383 return ResultCollector.Result->takeError();
384
385 std::vector<tooling::Replacement> Replacements;
386 for (const tooling::AtomicChange &Change : ResultCollector.Result->get()) {
387 tooling::Replacements ChangeReps = Change.getReplacements();
388 for (const auto &Rep : ChangeReps) {
389 // FIXME: Right now we only support renaming the main file, so we drop
390 // replacements not for the main file. In the future, we might consider to
391 // support:
392 // * rename in any included header
393 // * rename only in the "main" header
394 // * provide an error if there are symbols we won't rename (e.g.
395 // std::vector)
396 // * rename globally in project
397 // * rename in open files
398 if (Rep.getFilePath() == File)
399 Replacements.push_back(Rep);
400 }
401 }
402 return Replacements;
403}
404
Ilya Biryukov38d79772017-05-16 09:38:59 +0000405std::string ClangdServer::getDocument(PathRef File) {
406 auto draft = DraftMgr.getDraft(File);
407 assert(draft.Draft && "File is not tracked, cannot get contents");
408 return *draft.Draft;
409}
410
Ilya Biryukovf01af682017-05-23 13:42:59 +0000411std::string ClangdServer::dumpAST(PathRef File) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000412 std::shared_ptr<CppFile> Resources = Units.getFile(File);
413 assert(Resources && "dumpAST is called for non-added document");
Ilya Biryukov38d79772017-05-16 09:38:59 +0000414
Ilya Biryukov02d58702017-08-01 15:51:38 +0000415 std::string Result;
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +0000416 Resources->getAST().get()->runUnderLock([&Result](ParsedAST *AST) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000417 llvm::raw_string_ostream ResultOS(Result);
418 if (AST) {
419 clangd::dumpAST(*AST, ResultOS);
420 } else {
421 ResultOS << "<no-ast>";
422 }
423 ResultOS.flush();
Ilya Biryukovf01af682017-05-23 13:42:59 +0000424 });
Ilya Biryukov02d58702017-08-01 15:51:38 +0000425 return Result;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000426}
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000427
Benjamin Krameree19f162017-10-26 12:28:13 +0000428llvm::Expected<Tagged<std::vector<Location>>>
Ilya Biryukov940901e2017-12-13 12:51:22 +0000429ClangdServer::findDefinitions(const Context &Ctx, PathRef File, Position Pos) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000430 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
431
432 std::shared_ptr<CppFile> Resources = Units.getFile(File);
Benjamin Krameree19f162017-10-26 12:28:13 +0000433 if (!Resources)
434 return llvm::make_error<llvm::StringError>(
435 "findDefinitions called on non-added file",
436 llvm::errc::invalid_argument);
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000437
438 std::vector<Location> Result;
Ilya Biryukov940901e2017-12-13 12:51:22 +0000439 Resources->getAST().get()->runUnderLock([Pos, &Result, &Ctx](ParsedAST *AST) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000440 if (!AST)
441 return;
Ilya Biryukov940901e2017-12-13 12:51:22 +0000442 Result = clangd::findDefinitions(Ctx, *AST, Pos);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000443 });
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000444 return make_tagged(std::move(Result), TaggedFS.Tag);
445}
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000446
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000447llvm::Optional<Path> ClangdServer::switchSourceHeader(PathRef Path) {
448
449 StringRef SourceExtensions[] = {".cpp", ".c", ".cc", ".cxx",
450 ".c++", ".m", ".mm"};
451 StringRef HeaderExtensions[] = {".h", ".hh", ".hpp", ".hxx", ".inc"};
452
453 StringRef PathExt = llvm::sys::path::extension(Path);
454
455 // Lookup in a list of known extensions.
456 auto SourceIter =
457 std::find_if(std::begin(SourceExtensions), std::end(SourceExtensions),
458 [&PathExt](PathRef SourceExt) {
459 return SourceExt.equals_lower(PathExt);
460 });
461 bool IsSource = SourceIter != std::end(SourceExtensions);
462
463 auto HeaderIter =
464 std::find_if(std::begin(HeaderExtensions), std::end(HeaderExtensions),
465 [&PathExt](PathRef HeaderExt) {
466 return HeaderExt.equals_lower(PathExt);
467 });
468
469 bool IsHeader = HeaderIter != std::end(HeaderExtensions);
470
471 // We can only switch between extensions known extensions.
472 if (!IsSource && !IsHeader)
473 return llvm::None;
474
475 // Array to lookup extensions for the switch. An opposite of where original
476 // extension was found.
477 ArrayRef<StringRef> NewExts;
478 if (IsSource)
479 NewExts = HeaderExtensions;
480 else
481 NewExts = SourceExtensions;
482
483 // Storage for the new path.
484 SmallString<128> NewPath = StringRef(Path);
485
486 // Instance of vfs::FileSystem, used for file existence checks.
487 auto FS = FSProvider.getTaggedFileSystem(Path).Value;
488
489 // Loop through switched extension candidates.
490 for (StringRef NewExt : NewExts) {
491 llvm::sys::path::replace_extension(NewPath, NewExt);
492 if (FS->exists(NewPath))
493 return NewPath.str().str(); // First str() to convert from SmallString to
494 // StringRef, second to convert from StringRef
495 // to std::string
Ilya Biryukov33334942017-10-06 14:39:39 +0000496
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000497 // Also check NewExt in upper-case, just in case.
498 llvm::sys::path::replace_extension(NewPath, NewExt.upper());
499 if (FS->exists(NewPath))
500 return NewPath.str().str();
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000501 }
502
503 return llvm::None;
504}
505
Raoul Wols212bcf82017-12-12 20:25:06 +0000506llvm::Expected<tooling::Replacements>
507ClangdServer::formatCode(llvm::StringRef Code, PathRef File,
508 ArrayRef<tooling::Range> Ranges) {
509 // Call clang-format.
510 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
511 auto StyleOrError =
512 format::getStyle("file", File, "LLVM", Code, TaggedFS.Value.get());
513 if (!StyleOrError) {
514 return StyleOrError.takeError();
515 } else {
516 return format::reformat(StyleOrError.get(), Code, Ranges, File);
517 }
518}
519
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000520llvm::Expected<Tagged<std::vector<DocumentHighlight>>>
Ilya Biryukov940901e2017-12-13 12:51:22 +0000521ClangdServer::findDocumentHighlights(const Context &Ctx, PathRef File,
522 Position Pos) {
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000523 auto FileContents = DraftMgr.getDraft(File);
524 if (!FileContents.Draft)
525 return llvm::make_error<llvm::StringError>(
526 "findDocumentHighlights called on non-added file",
527 llvm::errc::invalid_argument);
528
529 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
530
531 std::shared_ptr<CppFile> Resources = Units.getFile(File);
532 if (!Resources)
533 return llvm::make_error<llvm::StringError>(
534 "findDocumentHighlights called on non-added file",
535 llvm::errc::invalid_argument);
536
537 std::vector<DocumentHighlight> Result;
538 llvm::Optional<llvm::Error> Err;
Ilya Biryukov940901e2017-12-13 12:51:22 +0000539 Resources->getAST().get()->runUnderLock([Pos, &Ctx, &Err,
540 &Result](ParsedAST *AST) {
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000541 if (!AST) {
542 Err = llvm::make_error<llvm::StringError>("Invalid AST",
543 llvm::errc::invalid_argument);
544 return;
545 }
Ilya Biryukov940901e2017-12-13 12:51:22 +0000546 Result = clangd::findDocumentHighlights(Ctx, *AST, Pos);
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000547 });
548
549 if (Err)
550 return std::move(*Err);
551 return make_tagged(Result, TaggedFS.Tag);
552}
553
Ilya Biryukov940901e2017-12-13 12:51:22 +0000554std::future<Context> ClangdServer::scheduleReparseAndDiags(
555 Context Ctx, PathRef File, VersionedDraft Contents,
556 std::shared_ptr<CppFile> Resources,
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000557 Tagged<IntrusiveRefCntPtr<vfs::FileSystem>> TaggedFS) {
558
559 assert(Contents.Draft && "Draft must have contents");
Ilya Biryukov940901e2017-12-13 12:51:22 +0000560 UniqueFunction<llvm::Optional<std::vector<DiagWithFixIts>>(const Context &)>
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000561 DeferredRebuild =
562 Resources->deferRebuild(*Contents.Draft, TaggedFS.Value);
Ilya Biryukov940901e2017-12-13 12:51:22 +0000563 std::promise<Context> DonePromise;
564 std::future<Context> DoneFuture = DonePromise.get_future();
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000565
566 DocVersion Version = Contents.Version;
567 Path FileStr = File;
568 VFSTag Tag = TaggedFS.Tag;
569 auto ReparseAndPublishDiags =
570 [this, FileStr, Version,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000571 Tag](UniqueFunction<llvm::Optional<std::vector<DiagWithFixIts>>(
572 const Context &)>
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000573 DeferredRebuild,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000574 std::promise<Context> DonePromise, Context Ctx) -> void {
575 auto Guard = onScopeExit([&]() { DonePromise.set_value(std::move(Ctx)); });
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000576
577 auto CurrentVersion = DraftMgr.getVersion(FileStr);
578 if (CurrentVersion != Version)
579 return; // This request is outdated
580
Ilya Biryukov940901e2017-12-13 12:51:22 +0000581 auto Diags = DeferredRebuild(Ctx);
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000582 if (!Diags)
583 return; // A new reparse was requested before this one completed.
Ilya Biryukov47f22022017-09-20 12:58:55 +0000584
585 // We need to serialize access to resulting diagnostics to avoid calling
586 // `onDiagnosticsReady` in the wrong order.
587 std::lock_guard<std::mutex> DiagsLock(DiagnosticsMutex);
588 DocVersion &LastReportedDiagsVersion = ReportedDiagnosticVersions[FileStr];
589 // FIXME(ibiryukov): get rid of '<' comparison here. In the current
590 // implementation diagnostics will not be reported after version counters'
591 // overflow. This should not happen in practice, since DocVersion is a
592 // 64-bit unsigned integer.
593 if (Version < LastReportedDiagsVersion)
594 return;
595 LastReportedDiagsVersion = Version;
596
Ilya Biryukov95558392018-01-10 17:59:27 +0000597 DiagConsumer.onDiagnosticsReady(Ctx, FileStr,
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000598 make_tagged(std::move(*Diags), Tag));
599 };
600
601 WorkScheduler.addToFront(std::move(ReparseAndPublishDiags),
Ilya Biryukov940901e2017-12-13 12:51:22 +0000602 std::move(DeferredRebuild), std::move(DonePromise),
603 std::move(Ctx));
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000604 return DoneFuture;
605}
606
Ilya Biryukov940901e2017-12-13 12:51:22 +0000607std::future<Context>
608ClangdServer::scheduleCancelRebuild(Context Ctx,
609 std::shared_ptr<CppFile> Resources) {
610 std::promise<Context> DonePromise;
611 std::future<Context> DoneFuture = DonePromise.get_future();
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000612 if (!Resources) {
613 // No need to schedule any cleanup.
Ilya Biryukov940901e2017-12-13 12:51:22 +0000614 DonePromise.set_value(std::move(Ctx));
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000615 return DoneFuture;
616 }
617
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000618 UniqueFunction<void()> DeferredCancel = Resources->deferCancelRebuild();
Ilya Biryukov940901e2017-12-13 12:51:22 +0000619 auto CancelReparses = [Resources](std::promise<Context> DonePromise,
620 UniqueFunction<void()> DeferredCancel,
621 Context Ctx) {
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000622 DeferredCancel();
Ilya Biryukov940901e2017-12-13 12:51:22 +0000623 DonePromise.set_value(std::move(Ctx));
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000624 };
625 WorkScheduler.addToFront(std::move(CancelReparses), std::move(DonePromise),
Ilya Biryukov940901e2017-12-13 12:51:22 +0000626 std::move(DeferredCancel), std::move(Ctx));
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000627 return DoneFuture;
628}
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000629
630void ClangdServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
631 // FIXME: Do nothing for now. This will be used for indexing and potentially
632 // invalidating other caches.
633}