blob: 4a9ee6999da2a79000b328b5a423949dfd5256f4 [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 McCallb536a2a2017-12-19 12:23:48 +000011#include "SourceCode.h"
Ilya Biryukovafb55542017-05-16 14:40:30 +000012#include "clang/Format/Format.h"
Ilya Biryukov38d79772017-05-16 09:38:59 +000013#include "clang/Frontend/CompilerInstance.h"
14#include "clang/Frontend/CompilerInvocation.h"
15#include "clang/Tooling/CompilationDatabase.h"
Ilya Biryukov9e11c4c2017-11-15 18:04:56 +000016#include "clang/Tooling/Refactoring/RefactoringResultConsumer.h"
17#include "clang/Tooling/Refactoring/Rename/RenamingAction.h"
Ilya Biryukovafb55542017-05-16 14:40:30 +000018#include "llvm/ADT/ArrayRef.h"
Benjamin Krameree19f162017-10-26 12:28:13 +000019#include "llvm/Support/Errc.h"
Ilya Biryukov38d79772017-05-16 09:38:59 +000020#include "llvm/Support/FileSystem.h"
Sam McCall8567cb32017-11-02 09:21:51 +000021#include "llvm/Support/FormatProviders.h"
22#include "llvm/Support/FormatVariadic.h"
Marc-Andre Laperle37de9712017-09-27 15:31:17 +000023#include "llvm/Support/Path.h"
Ilya Biryukovf01af682017-05-23 13:42:59 +000024#include "llvm/Support/raw_ostream.h"
25#include <future>
Ilya Biryukov38d79772017-05-16 09:38:59 +000026
Ilya Biryukov2f314102017-05-16 10:06:20 +000027using namespace clang;
Ilya Biryukov38d79772017-05-16 09:38:59 +000028using namespace clang::clangd;
29
Ilya Biryukovafb55542017-05-16 14:40:30 +000030namespace {
31
Ilya Biryukova46f7a92017-06-28 10:34:50 +000032std::string getStandardResourceDir() {
33 static int Dummy; // Just an address in this process.
34 return CompilerInvocation::GetResourcesPath("clangd", (void *)&Dummy);
35}
36
Haojian Wu345099c2017-11-09 11:30:04 +000037class RefactoringResultCollector final
38 : public tooling::RefactoringResultConsumer {
39public:
40 void handleError(llvm::Error Err) override {
41 assert(!Result.hasValue());
42 // FIXME: figure out a way to return better message for DiagnosticError.
43 // clangd uses llvm::toString to convert the Err to string, however, for
44 // DiagnosticError, only "clang diagnostic" will be generated.
45 Result = std::move(Err);
46 }
47
48 // Using the handle(SymbolOccurrences) from parent class.
49 using tooling::RefactoringResultConsumer::handle;
50
51 void handle(tooling::AtomicChanges SourceReplacements) override {
52 assert(!Result.hasValue());
53 Result = std::move(SourceReplacements);
54 }
55
56 Optional<Expected<tooling::AtomicChanges>> Result;
57};
58
Ilya Biryukovafb55542017-05-16 14:40:30 +000059} // namespace
60
Ilya Biryukov22602992017-05-30 15:11:02 +000061Tagged<IntrusiveRefCntPtr<vfs::FileSystem>>
Ilya Biryukovaf0c04b2017-06-14 09:46:44 +000062RealFileSystemProvider::getTaggedFileSystem(PathRef File) {
Ilya Biryukov22602992017-05-30 15:11:02 +000063 return make_tagged(vfs::getRealFileSystem(), VFSTag());
Ilya Biryukov0f62ed22017-05-26 12:26:51 +000064}
65
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +000066unsigned clangd::getDefaultAsyncThreadsCount() {
67 unsigned HardwareConcurrency = std::thread::hardware_concurrency();
68 // C++ standard says that hardware_concurrency()
69 // may return 0, fallback to 1 worker thread in
70 // that case.
71 if (HardwareConcurrency == 0)
72 return 1;
73 return HardwareConcurrency;
74}
75
76ClangdScheduler::ClangdScheduler(unsigned AsyncThreadsCount)
77 : RunSynchronously(AsyncThreadsCount == 0) {
Ilya Biryukov38d79772017-05-16 09:38:59 +000078 if (RunSynchronously) {
79 // Don't start the worker thread if we're running synchronously
80 return;
81 }
82
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +000083 Workers.reserve(AsyncThreadsCount);
84 for (unsigned I = 0; I < AsyncThreadsCount; ++I) {
Sam McCall8567cb32017-11-02 09:21:51 +000085 Workers.push_back(std::thread([this, I]() {
86 llvm::set_thread_name(llvm::formatv("scheduler/{0}", I));
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +000087 while (true) {
Ilya Biryukov08e6ccb2017-10-09 16:26:26 +000088 UniqueFunction<void()> Request;
Ilya Biryukov38d79772017-05-16 09:38:59 +000089
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +000090 // Pick request from the queue
91 {
92 std::unique_lock<std::mutex> Lock(Mutex);
93 // Wait for more requests.
94 RequestCV.wait(Lock,
95 [this] { return !RequestQueue.empty() || Done; });
96 if (Done)
97 return;
Ilya Biryukov38d79772017-05-16 09:38:59 +000098
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +000099 assert(!RequestQueue.empty() && "RequestQueue was empty");
Ilya Biryukov38d79772017-05-16 09:38:59 +0000100
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000101 // We process requests starting from the front of the queue. Users of
102 // ClangdScheduler have a way to prioritise their requests by putting
103 // them to the either side of the queue (using either addToEnd or
104 // addToFront).
105 Request = std::move(RequestQueue.front());
106 RequestQueue.pop_front();
107 } // unlock Mutex
Ilya Biryukov38d79772017-05-16 09:38:59 +0000108
Ilya Biryukov08e6ccb2017-10-09 16:26:26 +0000109 Request();
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000110 }
111 }));
112 }
Ilya Biryukov38d79772017-05-16 09:38:59 +0000113}
114
115ClangdScheduler::~ClangdScheduler() {
116 if (RunSynchronously)
117 return; // no worker thread is running in that case
118
119 {
120 std::lock_guard<std::mutex> Lock(Mutex);
121 // Wake up the worker thread
122 Done = true;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000123 } // unlock Mutex
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000124 RequestCV.notify_all();
125
126 for (auto &Worker : Workers)
127 Worker.join();
Ilya Biryukov38d79772017-05-16 09:38:59 +0000128}
129
Sam McCalladccab62017-11-23 16:58:22 +0000130ClangdServer::ClangdServer(GlobalCompilationDatabase &CDB,
131 DiagnosticsConsumer &DiagConsumer,
132 FileSystemProvider &FSProvider,
133 unsigned AsyncThreadsCount,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000134 bool StorePreamblesInMemory,
Sam McCalladccab62017-11-23 16:58:22 +0000135 llvm::Optional<StringRef> ResourceDir)
Ilya Biryukov940901e2017-12-13 12:51:22 +0000136 : CDB(CDB), DiagConsumer(DiagConsumer), FSProvider(FSProvider),
Ilya Biryukova46f7a92017-06-28 10:34:50 +0000137 ResourceDir(ResourceDir ? ResourceDir->str() : getStandardResourceDir()),
Ilya Biryukov38d79772017-05-16 09:38:59 +0000138 PCHs(std::make_shared<PCHContainerOperations>()),
Ilya Biryukove9eb7f02017-11-16 16:25:18 +0000139 StorePreamblesInMemory(StorePreamblesInMemory),
Ilya Biryukovd3b04e32017-12-05 10:42:57 +0000140 WorkScheduler(AsyncThreadsCount) {}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000141
Marc-Andre Laperle37de9712017-09-27 15:31:17 +0000142void ClangdServer::setRootPath(PathRef RootPath) {
143 std::string NewRootPath = llvm::sys::path::convert_to_slash(
144 RootPath, llvm::sys::path::Style::posix);
145 if (llvm::sys::fs::is_directory(NewRootPath))
146 this->RootPath = NewRootPath;
147}
148
Ilya Biryukov940901e2017-12-13 12:51:22 +0000149std::future<Context> ClangdServer::addDocument(Context Ctx, PathRef File,
150 StringRef Contents) {
Ilya Biryukovf01af682017-05-23 13:42:59 +0000151 DocVersion Version = DraftMgr.updateDraft(File, Contents);
Ilya Biryukovf01af682017-05-23 13:42:59 +0000152
Ilya Biryukov02d58702017-08-01 15:51:38 +0000153 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
Ilya Biryukove9eb7f02017-11-16 16:25:18 +0000154 std::shared_ptr<CppFile> Resources = Units.getOrCreateFile(
Ilya Biryukov940901e2017-12-13 12:51:22 +0000155 File, ResourceDir, CDB, StorePreamblesInMemory, PCHs);
156 return scheduleReparseAndDiags(std::move(Ctx), File,
157 VersionedDraft{Version, Contents.str()},
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000158 std::move(Resources), std::move(TaggedFS));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000159}
160
Ilya Biryukov940901e2017-12-13 12:51:22 +0000161std::future<Context> ClangdServer::removeDocument(Context Ctx, PathRef File) {
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000162 DraftMgr.removeDraft(File);
163 std::shared_ptr<CppFile> Resources = Units.removeIfPresent(File);
Ilya Biryukov940901e2017-12-13 12:51:22 +0000164 return scheduleCancelRebuild(std::move(Ctx), std::move(Resources));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000165}
166
Ilya Biryukov940901e2017-12-13 12:51:22 +0000167std::future<Context> ClangdServer::forceReparse(Context Ctx, PathRef File) {
Ilya Biryukov91dbf5b2017-08-14 08:37:32 +0000168 auto FileContents = DraftMgr.getDraft(File);
169 assert(FileContents.Draft &&
170 "forceReparse() was called for non-added document");
171
172 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
Ilya Biryukove9eb7f02017-11-16 16:25:18 +0000173 auto Recreated = Units.recreateFileIfCompileCommandChanged(
Ilya Biryukov940901e2017-12-13 12:51:22 +0000174 File, ResourceDir, CDB, StorePreamblesInMemory, PCHs);
Ilya Biryukov91dbf5b2017-08-14 08:37:32 +0000175
176 // Note that std::future from this cleanup action is ignored.
Ilya Biryukov940901e2017-12-13 12:51:22 +0000177 scheduleCancelRebuild(Ctx.clone(), std::move(Recreated.RemovedFile));
Ilya Biryukov91dbf5b2017-08-14 08:37:32 +0000178 // Schedule a reparse.
Ilya Biryukov940901e2017-12-13 12:51:22 +0000179 return scheduleReparseAndDiags(std::move(Ctx), File, std::move(FileContents),
Ilya Biryukov91dbf5b2017-08-14 08:37:32 +0000180 std::move(Recreated.FileInCollection),
181 std::move(TaggedFS));
Ilya Biryukov0f62ed22017-05-26 12:26:51 +0000182}
183
Ilya Biryukov940901e2017-12-13 12:51:22 +0000184std::future<std::pair<Context, Tagged<CompletionList>>>
185ClangdServer::codeComplete(Context Ctx, PathRef File, Position Pos,
Ilya Biryukovd3b04e32017-12-05 10:42:57 +0000186 const clangd::CodeCompleteOptions &Opts,
Ilya Biryukoved99e4c2017-07-31 17:09:29 +0000187 llvm::Optional<StringRef> OverridenContents,
188 IntrusiveRefCntPtr<vfs::FileSystem> *UsedFS) {
Ilya Biryukov940901e2017-12-13 12:51:22 +0000189 using ResultType = std::pair<Context, Tagged<CompletionList>>;
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000190
191 std::promise<ResultType> ResultPromise;
192
Ilya Biryukov940901e2017-12-13 12:51:22 +0000193 auto Callback = [](std::promise<ResultType> ResultPromise, Context Ctx,
194 Tagged<CompletionList> Result) -> void {
195 ResultPromise.set_value({std::move(Ctx), std::move(Result)});
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000196 };
197
198 std::future<ResultType> ResultFuture = ResultPromise.get_future();
Ilya Biryukov940901e2017-12-13 12:51:22 +0000199 codeComplete(std::move(Ctx), File, Pos, Opts,
200 BindWithForward(Callback, std::move(ResultPromise)),
201 OverridenContents, UsedFS);
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000202 return ResultFuture;
203}
204
205void ClangdServer::codeComplete(
Ilya Biryukov940901e2017-12-13 12:51:22 +0000206 Context Ctx, PathRef File, Position Pos,
207 const clangd::CodeCompleteOptions &Opts,
208 UniqueFunction<void(Context, Tagged<CompletionList>)> Callback,
Ilya Biryukovd3b04e32017-12-05 10:42:57 +0000209 llvm::Optional<StringRef> OverridenContents,
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000210 IntrusiveRefCntPtr<vfs::FileSystem> *UsedFS) {
Ilya Biryukov940901e2017-12-13 12:51:22 +0000211 using CallbackType = UniqueFunction<void(Context, Tagged<CompletionList>)>;
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000212
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000213 std::string Contents;
214 if (OverridenContents) {
215 Contents = *OverridenContents;
216 } else {
Ilya Biryukov0e27ce42017-06-13 14:15:56 +0000217 auto FileContents = DraftMgr.getDraft(File);
218 assert(FileContents.Draft &&
219 "codeComplete is called for non-added document");
220
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000221 Contents = std::move(*FileContents.Draft);
Ilya Biryukov0e27ce42017-06-13 14:15:56 +0000222 }
Ilya Biryukov38d79772017-05-16 09:38:59 +0000223
Ilya Biryukovaf0c04b2017-06-14 09:46:44 +0000224 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
Ilya Biryukoved99e4c2017-07-31 17:09:29 +0000225 if (UsedFS)
226 *UsedFS = TaggedFS.Value;
227
Ilya Biryukov02d58702017-08-01 15:51:38 +0000228 std::shared_ptr<CppFile> Resources = Units.getFile(File);
229 assert(Resources && "Calling completion on non-added file");
230
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000231 // Remember the current Preamble and use it when async task starts executing.
232 // At the point when async task starts executing, we may have a different
233 // Preamble in Resources. However, we assume the Preamble that we obtain here
234 // is reusable in completion more often.
235 std::shared_ptr<const PreambleData> Preamble =
236 Resources->getPossiblyStalePreamble();
Ilya Biryukovd3b04e32017-12-05 10:42:57 +0000237 // Copy completion options for passing them to async task handler.
238 auto CodeCompleteOpts = Opts;
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000239 // A task that will be run asynchronously.
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000240 auto Task =
241 // 'mutable' to reassign Preamble variable.
Ilya Biryukov940901e2017-12-13 12:51:22 +0000242 [=](Context Ctx, CallbackType Callback) mutable {
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000243 if (!Preamble) {
244 // Maybe we built some preamble before processing this request.
245 Preamble = Resources->getPossiblyStalePreamble();
246 }
247 // FIXME(ibiryukov): even if Preamble is non-null, we may want to check
248 // both the old and the new version in case only one of them matches.
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000249
Sam McCalla40371b2017-11-15 09:16:29 +0000250 CompletionList Result = clangd::codeComplete(
Ilya Biryukov940901e2017-12-13 12:51:22 +0000251 Ctx, File, Resources->getCompileCommand(),
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000252 Preamble ? &Preamble->Preamble : nullptr, Contents, Pos,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000253 TaggedFS.Value, PCHs, CodeCompleteOpts);
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000254
Ilya Biryukov940901e2017-12-13 12:51:22 +0000255 Callback(std::move(Ctx),
256 make_tagged(std::move(Result), std::move(TaggedFS.Tag)));
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000257 };
258
Ilya Biryukov940901e2017-12-13 12:51:22 +0000259 WorkScheduler.addToFront(std::move(Task), std::move(Ctx),
260 std::move(Callback));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000261}
Ilya Biryukovf01af682017-05-23 13:42:59 +0000262
Benjamin Krameree19f162017-10-26 12:28:13 +0000263llvm::Expected<Tagged<SignatureHelp>>
Ilya Biryukov940901e2017-12-13 12:51:22 +0000264ClangdServer::signatureHelp(const Context &Ctx, PathRef File, Position Pos,
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000265 llvm::Optional<StringRef> OverridenContents,
266 IntrusiveRefCntPtr<vfs::FileSystem> *UsedFS) {
267 std::string DraftStorage;
268 if (!OverridenContents) {
269 auto FileContents = DraftMgr.getDraft(File);
Benjamin Krameree19f162017-10-26 12:28:13 +0000270 if (!FileContents.Draft)
271 return llvm::make_error<llvm::StringError>(
272 "signatureHelp is called for non-added document",
273 llvm::errc::invalid_argument);
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000274
275 DraftStorage = std::move(*FileContents.Draft);
276 OverridenContents = DraftStorage;
277 }
278
279 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
280 if (UsedFS)
281 *UsedFS = TaggedFS.Value;
282
283 std::shared_ptr<CppFile> Resources = Units.getFile(File);
Benjamin Krameree19f162017-10-26 12:28:13 +0000284 if (!Resources)
285 return llvm::make_error<llvm::StringError>(
286 "signatureHelp is called for non-added document",
287 llvm::errc::invalid_argument);
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000288
289 auto Preamble = Resources->getPossiblyStalePreamble();
Ilya Biryukov940901e2017-12-13 12:51:22 +0000290 auto Result =
291 clangd::signatureHelp(Ctx, File, Resources->getCompileCommand(),
292 Preamble ? &Preamble->Preamble : nullptr,
293 *OverridenContents, Pos, TaggedFS.Value, PCHs);
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000294 return make_tagged(std::move(Result), TaggedFS.Tag);
295}
296
Raoul Wols212bcf82017-12-12 20:25:06 +0000297llvm::Expected<tooling::Replacements>
298ClangdServer::formatRange(StringRef Code, PathRef File, Range Rng) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000299 size_t Begin = positionToOffset(Code, Rng.start);
300 size_t Len = positionToOffset(Code, Rng.end) - Begin;
301 return formatCode(Code, File, {tooling::Range(Begin, Len)});
302}
303
Raoul Wols212bcf82017-12-12 20:25:06 +0000304llvm::Expected<tooling::Replacements> ClangdServer::formatFile(StringRef Code,
305 PathRef File) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000306 // Format everything.
Ilya Biryukovafb55542017-05-16 14:40:30 +0000307 return formatCode(Code, File, {tooling::Range(0, Code.size())});
308}
309
Raoul Wols212bcf82017-12-12 20:25:06 +0000310llvm::Expected<tooling::Replacements>
311ClangdServer::formatOnType(StringRef Code, PathRef File, Position Pos) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000312 // Look for the previous opening brace from the character position and
313 // format starting from there.
Ilya Biryukovafb55542017-05-16 14:40:30 +0000314 size_t CursorPos = positionToOffset(Code, Pos);
315 size_t PreviousLBracePos = StringRef(Code).find_last_of('{', CursorPos);
316 if (PreviousLBracePos == StringRef::npos)
317 PreviousLBracePos = CursorPos;
Sam McCallb536a2a2017-12-19 12:23:48 +0000318 size_t Len = CursorPos - PreviousLBracePos;
Ilya Biryukovafb55542017-05-16 14:40:30 +0000319
320 return formatCode(Code, File, {tooling::Range(PreviousLBracePos, Len)});
321}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000322
Haojian Wu345099c2017-11-09 11:30:04 +0000323Expected<std::vector<tooling::Replacement>>
Ilya Biryukov940901e2017-12-13 12:51:22 +0000324ClangdServer::rename(const Context &Ctx, PathRef File, Position Pos,
325 llvm::StringRef NewName) {
Haojian Wu345099c2017-11-09 11:30:04 +0000326 std::string Code = getDocument(File);
327 std::shared_ptr<CppFile> Resources = Units.getFile(File);
328 RefactoringResultCollector ResultCollector;
329 Resources->getAST().get()->runUnderLock([&](ParsedAST *AST) {
330 const SourceManager &SourceMgr = AST->getASTContext().getSourceManager();
331 const FileEntry *FE =
332 SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
333 if (!FE)
334 return;
335 SourceLocation SourceLocationBeg =
336 clangd::getBeginningOfIdentifier(*AST, Pos, FE);
337 tooling::RefactoringRuleContext Context(
338 AST->getASTContext().getSourceManager());
339 Context.setASTContext(AST->getASTContext());
340 auto Rename = clang::tooling::RenameOccurrences::initiate(
341 Context, SourceRange(SourceLocationBeg), NewName.str());
342 if (!Rename) {
343 ResultCollector.Result = Rename.takeError();
344 return;
345 }
346 Rename->invoke(ResultCollector, Context);
347 });
348 assert(ResultCollector.Result.hasValue());
349 if (!ResultCollector.Result.getValue())
350 return ResultCollector.Result->takeError();
351
352 std::vector<tooling::Replacement> Replacements;
353 for (const tooling::AtomicChange &Change : ResultCollector.Result->get()) {
354 tooling::Replacements ChangeReps = Change.getReplacements();
355 for (const auto &Rep : ChangeReps) {
356 // FIXME: Right now we only support renaming the main file, so we drop
357 // replacements not for the main file. In the future, we might consider to
358 // support:
359 // * rename in any included header
360 // * rename only in the "main" header
361 // * provide an error if there are symbols we won't rename (e.g.
362 // std::vector)
363 // * rename globally in project
364 // * rename in open files
365 if (Rep.getFilePath() == File)
366 Replacements.push_back(Rep);
367 }
368 }
369 return Replacements;
370}
371
Ilya Biryukov38d79772017-05-16 09:38:59 +0000372std::string ClangdServer::getDocument(PathRef File) {
373 auto draft = DraftMgr.getDraft(File);
374 assert(draft.Draft && "File is not tracked, cannot get contents");
375 return *draft.Draft;
376}
377
Ilya Biryukovf01af682017-05-23 13:42:59 +0000378std::string ClangdServer::dumpAST(PathRef File) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000379 std::shared_ptr<CppFile> Resources = Units.getFile(File);
380 assert(Resources && "dumpAST is called for non-added document");
Ilya Biryukov38d79772017-05-16 09:38:59 +0000381
Ilya Biryukov02d58702017-08-01 15:51:38 +0000382 std::string Result;
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +0000383 Resources->getAST().get()->runUnderLock([&Result](ParsedAST *AST) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000384 llvm::raw_string_ostream ResultOS(Result);
385 if (AST) {
386 clangd::dumpAST(*AST, ResultOS);
387 } else {
388 ResultOS << "<no-ast>";
389 }
390 ResultOS.flush();
Ilya Biryukovf01af682017-05-23 13:42:59 +0000391 });
Ilya Biryukov02d58702017-08-01 15:51:38 +0000392 return Result;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000393}
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000394
Benjamin Krameree19f162017-10-26 12:28:13 +0000395llvm::Expected<Tagged<std::vector<Location>>>
Ilya Biryukov940901e2017-12-13 12:51:22 +0000396ClangdServer::findDefinitions(const Context &Ctx, PathRef File, Position Pos) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000397 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
398
399 std::shared_ptr<CppFile> Resources = Units.getFile(File);
Benjamin Krameree19f162017-10-26 12:28:13 +0000400 if (!Resources)
401 return llvm::make_error<llvm::StringError>(
402 "findDefinitions called on non-added file",
403 llvm::errc::invalid_argument);
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000404
405 std::vector<Location> Result;
Ilya Biryukov940901e2017-12-13 12:51:22 +0000406 Resources->getAST().get()->runUnderLock([Pos, &Result, &Ctx](ParsedAST *AST) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000407 if (!AST)
408 return;
Ilya Biryukov940901e2017-12-13 12:51:22 +0000409 Result = clangd::findDefinitions(Ctx, *AST, Pos);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000410 });
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000411 return make_tagged(std::move(Result), TaggedFS.Tag);
412}
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000413
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000414llvm::Optional<Path> ClangdServer::switchSourceHeader(PathRef Path) {
415
416 StringRef SourceExtensions[] = {".cpp", ".c", ".cc", ".cxx",
417 ".c++", ".m", ".mm"};
418 StringRef HeaderExtensions[] = {".h", ".hh", ".hpp", ".hxx", ".inc"};
419
420 StringRef PathExt = llvm::sys::path::extension(Path);
421
422 // Lookup in a list of known extensions.
423 auto SourceIter =
424 std::find_if(std::begin(SourceExtensions), std::end(SourceExtensions),
425 [&PathExt](PathRef SourceExt) {
426 return SourceExt.equals_lower(PathExt);
427 });
428 bool IsSource = SourceIter != std::end(SourceExtensions);
429
430 auto HeaderIter =
431 std::find_if(std::begin(HeaderExtensions), std::end(HeaderExtensions),
432 [&PathExt](PathRef HeaderExt) {
433 return HeaderExt.equals_lower(PathExt);
434 });
435
436 bool IsHeader = HeaderIter != std::end(HeaderExtensions);
437
438 // We can only switch between extensions known extensions.
439 if (!IsSource && !IsHeader)
440 return llvm::None;
441
442 // Array to lookup extensions for the switch. An opposite of where original
443 // extension was found.
444 ArrayRef<StringRef> NewExts;
445 if (IsSource)
446 NewExts = HeaderExtensions;
447 else
448 NewExts = SourceExtensions;
449
450 // Storage for the new path.
451 SmallString<128> NewPath = StringRef(Path);
452
453 // Instance of vfs::FileSystem, used for file existence checks.
454 auto FS = FSProvider.getTaggedFileSystem(Path).Value;
455
456 // Loop through switched extension candidates.
457 for (StringRef NewExt : NewExts) {
458 llvm::sys::path::replace_extension(NewPath, NewExt);
459 if (FS->exists(NewPath))
460 return NewPath.str().str(); // First str() to convert from SmallString to
461 // StringRef, second to convert from StringRef
462 // to std::string
Ilya Biryukov33334942017-10-06 14:39:39 +0000463
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000464 // Also check NewExt in upper-case, just in case.
465 llvm::sys::path::replace_extension(NewPath, NewExt.upper());
466 if (FS->exists(NewPath))
467 return NewPath.str().str();
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000468 }
469
470 return llvm::None;
471}
472
Raoul Wols212bcf82017-12-12 20:25:06 +0000473llvm::Expected<tooling::Replacements>
474ClangdServer::formatCode(llvm::StringRef Code, PathRef File,
475 ArrayRef<tooling::Range> Ranges) {
476 // Call clang-format.
477 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
478 auto StyleOrError =
479 format::getStyle("file", File, "LLVM", Code, TaggedFS.Value.get());
480 if (!StyleOrError) {
481 return StyleOrError.takeError();
482 } else {
483 return format::reformat(StyleOrError.get(), Code, Ranges, File);
484 }
485}
486
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000487llvm::Expected<Tagged<std::vector<DocumentHighlight>>>
Ilya Biryukov940901e2017-12-13 12:51:22 +0000488ClangdServer::findDocumentHighlights(const Context &Ctx, PathRef File,
489 Position Pos) {
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000490 auto FileContents = DraftMgr.getDraft(File);
491 if (!FileContents.Draft)
492 return llvm::make_error<llvm::StringError>(
493 "findDocumentHighlights called on non-added file",
494 llvm::errc::invalid_argument);
495
496 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
497
498 std::shared_ptr<CppFile> Resources = Units.getFile(File);
499 if (!Resources)
500 return llvm::make_error<llvm::StringError>(
501 "findDocumentHighlights called on non-added file",
502 llvm::errc::invalid_argument);
503
504 std::vector<DocumentHighlight> Result;
505 llvm::Optional<llvm::Error> Err;
Ilya Biryukov940901e2017-12-13 12:51:22 +0000506 Resources->getAST().get()->runUnderLock([Pos, &Ctx, &Err,
507 &Result](ParsedAST *AST) {
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000508 if (!AST) {
509 Err = llvm::make_error<llvm::StringError>("Invalid AST",
510 llvm::errc::invalid_argument);
511 return;
512 }
Ilya Biryukov940901e2017-12-13 12:51:22 +0000513 Result = clangd::findDocumentHighlights(Ctx, *AST, Pos);
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000514 });
515
516 if (Err)
517 return std::move(*Err);
518 return make_tagged(Result, TaggedFS.Tag);
519}
520
Ilya Biryukov940901e2017-12-13 12:51:22 +0000521std::future<Context> ClangdServer::scheduleReparseAndDiags(
522 Context Ctx, PathRef File, VersionedDraft Contents,
523 std::shared_ptr<CppFile> Resources,
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000524 Tagged<IntrusiveRefCntPtr<vfs::FileSystem>> TaggedFS) {
525
526 assert(Contents.Draft && "Draft must have contents");
Ilya Biryukov940901e2017-12-13 12:51:22 +0000527 UniqueFunction<llvm::Optional<std::vector<DiagWithFixIts>>(const Context &)>
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000528 DeferredRebuild =
529 Resources->deferRebuild(*Contents.Draft, TaggedFS.Value);
Ilya Biryukov940901e2017-12-13 12:51:22 +0000530 std::promise<Context> DonePromise;
531 std::future<Context> DoneFuture = DonePromise.get_future();
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000532
533 DocVersion Version = Contents.Version;
534 Path FileStr = File;
535 VFSTag Tag = TaggedFS.Tag;
536 auto ReparseAndPublishDiags =
537 [this, FileStr, Version,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000538 Tag](UniqueFunction<llvm::Optional<std::vector<DiagWithFixIts>>(
539 const Context &)>
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000540 DeferredRebuild,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000541 std::promise<Context> DonePromise, Context Ctx) -> void {
542 auto Guard = onScopeExit([&]() { DonePromise.set_value(std::move(Ctx)); });
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000543
544 auto CurrentVersion = DraftMgr.getVersion(FileStr);
545 if (CurrentVersion != Version)
546 return; // This request is outdated
547
Ilya Biryukov940901e2017-12-13 12:51:22 +0000548 auto Diags = DeferredRebuild(Ctx);
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000549 if (!Diags)
550 return; // A new reparse was requested before this one completed.
Ilya Biryukov47f22022017-09-20 12:58:55 +0000551
552 // We need to serialize access to resulting diagnostics to avoid calling
553 // `onDiagnosticsReady` in the wrong order.
554 std::lock_guard<std::mutex> DiagsLock(DiagnosticsMutex);
555 DocVersion &LastReportedDiagsVersion = ReportedDiagnosticVersions[FileStr];
556 // FIXME(ibiryukov): get rid of '<' comparison here. In the current
557 // implementation diagnostics will not be reported after version counters'
558 // overflow. This should not happen in practice, since DocVersion is a
559 // 64-bit unsigned integer.
560 if (Version < LastReportedDiagsVersion)
561 return;
562 LastReportedDiagsVersion = Version;
563
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000564 DiagConsumer.onDiagnosticsReady(FileStr,
565 make_tagged(std::move(*Diags), Tag));
566 };
567
568 WorkScheduler.addToFront(std::move(ReparseAndPublishDiags),
Ilya Biryukov940901e2017-12-13 12:51:22 +0000569 std::move(DeferredRebuild), std::move(DonePromise),
570 std::move(Ctx));
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000571 return DoneFuture;
572}
573
Ilya Biryukov940901e2017-12-13 12:51:22 +0000574std::future<Context>
575ClangdServer::scheduleCancelRebuild(Context Ctx,
576 std::shared_ptr<CppFile> Resources) {
577 std::promise<Context> DonePromise;
578 std::future<Context> DoneFuture = DonePromise.get_future();
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000579 if (!Resources) {
580 // No need to schedule any cleanup.
Ilya Biryukov940901e2017-12-13 12:51:22 +0000581 DonePromise.set_value(std::move(Ctx));
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000582 return DoneFuture;
583 }
584
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000585 UniqueFunction<void()> DeferredCancel = Resources->deferCancelRebuild();
Ilya Biryukov940901e2017-12-13 12:51:22 +0000586 auto CancelReparses = [Resources](std::promise<Context> DonePromise,
587 UniqueFunction<void()> DeferredCancel,
588 Context Ctx) {
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000589 DeferredCancel();
Ilya Biryukov940901e2017-12-13 12:51:22 +0000590 DonePromise.set_value(std::move(Ctx));
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000591 };
592 WorkScheduler.addToFront(std::move(CancelReparses), std::move(DonePromise),
Ilya Biryukov940901e2017-12-13 12:51:22 +0000593 std::move(DeferredCancel), std::move(Ctx));
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000594 return DoneFuture;
595}
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000596
597void ClangdServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
598 // FIXME: Do nothing for now. This will be used for indexing and potentially
599 // invalidating other caches.
600}