blob: 928f35120fbb7a54f6f139caddea7291ff319090 [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::shared_ptr<CppFile> Resources = Units.getFile(File);
360 RefactoringResultCollector ResultCollector;
361 Resources->getAST().get()->runUnderLock([&](ParsedAST *AST) {
362 const SourceManager &SourceMgr = AST->getASTContext().getSourceManager();
363 const FileEntry *FE =
364 SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
365 if (!FE)
366 return;
367 SourceLocation SourceLocationBeg =
368 clangd::getBeginningOfIdentifier(*AST, Pos, FE);
369 tooling::RefactoringRuleContext Context(
370 AST->getASTContext().getSourceManager());
371 Context.setASTContext(AST->getASTContext());
372 auto Rename = clang::tooling::RenameOccurrences::initiate(
373 Context, SourceRange(SourceLocationBeg), NewName.str());
374 if (!Rename) {
375 ResultCollector.Result = Rename.takeError();
376 return;
377 }
378 Rename->invoke(ResultCollector, Context);
379 });
380 assert(ResultCollector.Result.hasValue());
381 if (!ResultCollector.Result.getValue())
382 return ResultCollector.Result->takeError();
383
384 std::vector<tooling::Replacement> Replacements;
385 for (const tooling::AtomicChange &Change : ResultCollector.Result->get()) {
386 tooling::Replacements ChangeReps = Change.getReplacements();
387 for (const auto &Rep : ChangeReps) {
388 // FIXME: Right now we only support renaming the main file, so we drop
389 // replacements not for the main file. In the future, we might consider to
390 // support:
391 // * rename in any included header
392 // * rename only in the "main" header
393 // * provide an error if there are symbols we won't rename (e.g.
394 // std::vector)
395 // * rename globally in project
396 // * rename in open files
397 if (Rep.getFilePath() == File)
398 Replacements.push_back(Rep);
399 }
400 }
401 return Replacements;
402}
403
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000404llvm::Optional<std::string> ClangdServer::getDocument(PathRef File) {
405 auto Latest = DraftMgr.getDraft(File);
406 if (!Latest.Draft)
407 return llvm::None;
408 return std::move(*Latest.Draft);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000409}
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);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000413 if (!Resources)
414 return "<non-added file>";
Ilya Biryukov38d79772017-05-16 09:38:59 +0000415
Ilya Biryukov02d58702017-08-01 15:51:38 +0000416 std::string Result;
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +0000417 Resources->getAST().get()->runUnderLock([&Result](ParsedAST *AST) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000418 llvm::raw_string_ostream ResultOS(Result);
419 if (AST) {
420 clangd::dumpAST(*AST, ResultOS);
421 } else {
422 ResultOS << "<no-ast>";
423 }
424 ResultOS.flush();
Ilya Biryukovf01af682017-05-23 13:42:59 +0000425 });
Ilya Biryukov02d58702017-08-01 15:51:38 +0000426 return Result;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000427}
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000428
Benjamin Krameree19f162017-10-26 12:28:13 +0000429llvm::Expected<Tagged<std::vector<Location>>>
Ilya Biryukov940901e2017-12-13 12:51:22 +0000430ClangdServer::findDefinitions(const Context &Ctx, PathRef File, Position Pos) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000431 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
432
433 std::shared_ptr<CppFile> Resources = Units.getFile(File);
Benjamin Krameree19f162017-10-26 12:28:13 +0000434 if (!Resources)
435 return llvm::make_error<llvm::StringError>(
436 "findDefinitions called on non-added file",
437 llvm::errc::invalid_argument);
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000438
439 std::vector<Location> Result;
Ilya Biryukov940901e2017-12-13 12:51:22 +0000440 Resources->getAST().get()->runUnderLock([Pos, &Result, &Ctx](ParsedAST *AST) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000441 if (!AST)
442 return;
Ilya Biryukov940901e2017-12-13 12:51:22 +0000443 Result = clangd::findDefinitions(Ctx, *AST, Pos);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000444 });
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000445 return make_tagged(std::move(Result), TaggedFS.Tag);
446}
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000447
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000448llvm::Optional<Path> ClangdServer::switchSourceHeader(PathRef Path) {
449
450 StringRef SourceExtensions[] = {".cpp", ".c", ".cc", ".cxx",
451 ".c++", ".m", ".mm"};
452 StringRef HeaderExtensions[] = {".h", ".hh", ".hpp", ".hxx", ".inc"};
453
454 StringRef PathExt = llvm::sys::path::extension(Path);
455
456 // Lookup in a list of known extensions.
457 auto SourceIter =
458 std::find_if(std::begin(SourceExtensions), std::end(SourceExtensions),
459 [&PathExt](PathRef SourceExt) {
460 return SourceExt.equals_lower(PathExt);
461 });
462 bool IsSource = SourceIter != std::end(SourceExtensions);
463
464 auto HeaderIter =
465 std::find_if(std::begin(HeaderExtensions), std::end(HeaderExtensions),
466 [&PathExt](PathRef HeaderExt) {
467 return HeaderExt.equals_lower(PathExt);
468 });
469
470 bool IsHeader = HeaderIter != std::end(HeaderExtensions);
471
472 // We can only switch between extensions known extensions.
473 if (!IsSource && !IsHeader)
474 return llvm::None;
475
476 // Array to lookup extensions for the switch. An opposite of where original
477 // extension was found.
478 ArrayRef<StringRef> NewExts;
479 if (IsSource)
480 NewExts = HeaderExtensions;
481 else
482 NewExts = SourceExtensions;
483
484 // Storage for the new path.
485 SmallString<128> NewPath = StringRef(Path);
486
487 // Instance of vfs::FileSystem, used for file existence checks.
488 auto FS = FSProvider.getTaggedFileSystem(Path).Value;
489
490 // Loop through switched extension candidates.
491 for (StringRef NewExt : NewExts) {
492 llvm::sys::path::replace_extension(NewPath, NewExt);
493 if (FS->exists(NewPath))
494 return NewPath.str().str(); // First str() to convert from SmallString to
495 // StringRef, second to convert from StringRef
496 // to std::string
Ilya Biryukov33334942017-10-06 14:39:39 +0000497
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000498 // Also check NewExt in upper-case, just in case.
499 llvm::sys::path::replace_extension(NewPath, NewExt.upper());
500 if (FS->exists(NewPath))
501 return NewPath.str().str();
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000502 }
503
504 return llvm::None;
505}
506
Raoul Wols212bcf82017-12-12 20:25:06 +0000507llvm::Expected<tooling::Replacements>
508ClangdServer::formatCode(llvm::StringRef Code, PathRef File,
509 ArrayRef<tooling::Range> Ranges) {
510 // Call clang-format.
511 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
512 auto StyleOrError =
513 format::getStyle("file", File, "LLVM", Code, TaggedFS.Value.get());
514 if (!StyleOrError) {
515 return StyleOrError.takeError();
516 } else {
517 return format::reformat(StyleOrError.get(), Code, Ranges, File);
518 }
519}
520
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000521llvm::Expected<Tagged<std::vector<DocumentHighlight>>>
Ilya Biryukov940901e2017-12-13 12:51:22 +0000522ClangdServer::findDocumentHighlights(const Context &Ctx, PathRef File,
523 Position Pos) {
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000524 auto FileContents = DraftMgr.getDraft(File);
525 if (!FileContents.Draft)
526 return llvm::make_error<llvm::StringError>(
527 "findDocumentHighlights called on non-added file",
528 llvm::errc::invalid_argument);
529
530 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
531
532 std::shared_ptr<CppFile> Resources = Units.getFile(File);
533 if (!Resources)
534 return llvm::make_error<llvm::StringError>(
535 "findDocumentHighlights called on non-added file",
536 llvm::errc::invalid_argument);
537
538 std::vector<DocumentHighlight> Result;
539 llvm::Optional<llvm::Error> Err;
Ilya Biryukov940901e2017-12-13 12:51:22 +0000540 Resources->getAST().get()->runUnderLock([Pos, &Ctx, &Err,
541 &Result](ParsedAST *AST) {
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000542 if (!AST) {
543 Err = llvm::make_error<llvm::StringError>("Invalid AST",
544 llvm::errc::invalid_argument);
545 return;
546 }
Ilya Biryukov940901e2017-12-13 12:51:22 +0000547 Result = clangd::findDocumentHighlights(Ctx, *AST, Pos);
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000548 });
549
550 if (Err)
551 return std::move(*Err);
552 return make_tagged(Result, TaggedFS.Tag);
553}
554
Ilya Biryukov940901e2017-12-13 12:51:22 +0000555std::future<Context> ClangdServer::scheduleReparseAndDiags(
556 Context Ctx, PathRef File, VersionedDraft Contents,
557 std::shared_ptr<CppFile> Resources,
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000558 Tagged<IntrusiveRefCntPtr<vfs::FileSystem>> TaggedFS) {
559
560 assert(Contents.Draft && "Draft must have contents");
Ilya Biryukov940901e2017-12-13 12:51:22 +0000561 UniqueFunction<llvm::Optional<std::vector<DiagWithFixIts>>(const Context &)>
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000562 DeferredRebuild =
563 Resources->deferRebuild(*Contents.Draft, TaggedFS.Value);
Ilya Biryukov940901e2017-12-13 12:51:22 +0000564 std::promise<Context> DonePromise;
565 std::future<Context> DoneFuture = DonePromise.get_future();
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000566
567 DocVersion Version = Contents.Version;
568 Path FileStr = File;
569 VFSTag Tag = TaggedFS.Tag;
570 auto ReparseAndPublishDiags =
571 [this, FileStr, Version,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000572 Tag](UniqueFunction<llvm::Optional<std::vector<DiagWithFixIts>>(
573 const Context &)>
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000574 DeferredRebuild,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000575 std::promise<Context> DonePromise, Context Ctx) -> void {
576 auto Guard = onScopeExit([&]() { DonePromise.set_value(std::move(Ctx)); });
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000577
578 auto CurrentVersion = DraftMgr.getVersion(FileStr);
579 if (CurrentVersion != Version)
580 return; // This request is outdated
581
Ilya Biryukov940901e2017-12-13 12:51:22 +0000582 auto Diags = DeferredRebuild(Ctx);
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000583 if (!Diags)
584 return; // A new reparse was requested before this one completed.
Ilya Biryukov47f22022017-09-20 12:58:55 +0000585
586 // We need to serialize access to resulting diagnostics to avoid calling
587 // `onDiagnosticsReady` in the wrong order.
588 std::lock_guard<std::mutex> DiagsLock(DiagnosticsMutex);
589 DocVersion &LastReportedDiagsVersion = ReportedDiagnosticVersions[FileStr];
590 // FIXME(ibiryukov): get rid of '<' comparison here. In the current
591 // implementation diagnostics will not be reported after version counters'
592 // overflow. This should not happen in practice, since DocVersion is a
593 // 64-bit unsigned integer.
594 if (Version < LastReportedDiagsVersion)
595 return;
596 LastReportedDiagsVersion = Version;
597
Ilya Biryukov95558392018-01-10 17:59:27 +0000598 DiagConsumer.onDiagnosticsReady(Ctx, FileStr,
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000599 make_tagged(std::move(*Diags), Tag));
600 };
601
602 WorkScheduler.addToFront(std::move(ReparseAndPublishDiags),
Ilya Biryukov940901e2017-12-13 12:51:22 +0000603 std::move(DeferredRebuild), std::move(DonePromise),
604 std::move(Ctx));
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000605 return DoneFuture;
606}
607
Ilya Biryukov940901e2017-12-13 12:51:22 +0000608std::future<Context>
609ClangdServer::scheduleCancelRebuild(Context Ctx,
610 std::shared_ptr<CppFile> Resources) {
611 std::promise<Context> DonePromise;
612 std::future<Context> DoneFuture = DonePromise.get_future();
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000613 if (!Resources) {
614 // No need to schedule any cleanup.
Ilya Biryukov940901e2017-12-13 12:51:22 +0000615 DonePromise.set_value(std::move(Ctx));
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000616 return DoneFuture;
617 }
618
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000619 UniqueFunction<void()> DeferredCancel = Resources->deferCancelRebuild();
Ilya Biryukov940901e2017-12-13 12:51:22 +0000620 auto CancelReparses = [Resources](std::promise<Context> DonePromise,
621 UniqueFunction<void()> DeferredCancel,
622 Context Ctx) {
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000623 DeferredCancel();
Ilya Biryukov940901e2017-12-13 12:51:22 +0000624 DonePromise.set_value(std::move(Ctx));
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000625 };
626 WorkScheduler.addToFront(std::move(CancelReparses), std::move(DonePromise),
Ilya Biryukov940901e2017-12-13 12:51:22 +0000627 std::move(DeferredCancel), std::move(Ctx));
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000628 return DoneFuture;
629}
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000630
631void ClangdServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
632 // FIXME: Do nothing for now. This will be used for indexing and potentially
633 // invalidating other caches.
634}