blob: 3b7c662e2e905006aa444f3241babd1501eb697e [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"
Ilya Biryukovafb55542017-05-16 14:40:30 +000011#include "clang/Format/Format.h"
Ilya Biryukov38d79772017-05-16 09:38:59 +000012#include "clang/Frontend/ASTUnit.h"
13#include "clang/Frontend/CompilerInstance.h"
14#include "clang/Frontend/CompilerInvocation.h"
15#include "clang/Tooling/CompilationDatabase.h"
Ilya Biryukovafb55542017-05-16 14:40:30 +000016#include "llvm/ADT/ArrayRef.h"
Ilya Biryukov38d79772017-05-16 09:38:59 +000017#include "llvm/Support/FileSystem.h"
Ilya Biryukovf01af682017-05-23 13:42:59 +000018#include "llvm/Support/raw_ostream.h"
19#include <future>
Ilya Biryukov38d79772017-05-16 09:38:59 +000020
Ilya Biryukov2f314102017-05-16 10:06:20 +000021using namespace clang;
Ilya Biryukov38d79772017-05-16 09:38:59 +000022using namespace clang::clangd;
23
Ilya Biryukovafb55542017-05-16 14:40:30 +000024namespace {
25
Ilya Biryukov02d58702017-08-01 15:51:38 +000026class FulfillPromiseGuard {
27public:
28 FulfillPromiseGuard(std::promise<void> &Promise) : Promise(Promise) {}
29
30 ~FulfillPromiseGuard() { Promise.set_value(); }
31
32private:
33 std::promise<void> &Promise;
34};
35
Ilya Biryukovafb55542017-05-16 14:40:30 +000036std::vector<tooling::Replacement> formatCode(StringRef Code, StringRef Filename,
37 ArrayRef<tooling::Range> Ranges) {
38 // Call clang-format.
39 // FIXME: Don't ignore style.
40 format::FormatStyle Style = format::getLLVMStyle();
41 auto Result = format::reformat(Style, Code, Ranges, Filename);
42
43 return std::vector<tooling::Replacement>(Result.begin(), Result.end());
44}
45
Ilya Biryukova46f7a92017-06-28 10:34:50 +000046std::string getStandardResourceDir() {
47 static int Dummy; // Just an address in this process.
48 return CompilerInvocation::GetResourcesPath("clangd", (void *)&Dummy);
49}
50
Ilya Biryukovafb55542017-05-16 14:40:30 +000051} // namespace
52
53size_t clangd::positionToOffset(StringRef Code, Position P) {
54 size_t Offset = 0;
55 for (int I = 0; I != P.line; ++I) {
56 // FIXME: \r\n
57 // FIXME: UTF-8
58 size_t F = Code.find('\n', Offset);
59 if (F == StringRef::npos)
60 return 0; // FIXME: Is this reasonable?
61 Offset = F + 1;
62 }
63 return (Offset == 0 ? 0 : (Offset - 1)) + P.character;
64}
65
66/// Turn an offset in Code into a [line, column] pair.
67Position clangd::offsetToPosition(StringRef Code, size_t Offset) {
68 StringRef JustBefore = Code.substr(0, Offset);
69 // FIXME: \r\n
70 // FIXME: UTF-8
71 int Lines = JustBefore.count('\n');
72 int Cols = JustBefore.size() - JustBefore.rfind('\n') - 1;
73 return {Lines, Cols};
74}
75
Ilya Biryukov22602992017-05-30 15:11:02 +000076Tagged<IntrusiveRefCntPtr<vfs::FileSystem>>
Ilya Biryukovaf0c04b2017-06-14 09:46:44 +000077RealFileSystemProvider::getTaggedFileSystem(PathRef File) {
Ilya Biryukov22602992017-05-30 15:11:02 +000078 return make_tagged(vfs::getRealFileSystem(), VFSTag());
Ilya Biryukov0f62ed22017-05-26 12:26:51 +000079}
80
Ilya Biryukovf01af682017-05-23 13:42:59 +000081ClangdScheduler::ClangdScheduler(bool RunSynchronously)
Ilya Biryukov38d79772017-05-16 09:38:59 +000082 : RunSynchronously(RunSynchronously) {
83 if (RunSynchronously) {
84 // Don't start the worker thread if we're running synchronously
85 return;
86 }
87
88 // Initialize Worker in ctor body, rather than init list to avoid potentially
89 // using not-yet-initialized members
Ilya Biryukovf01af682017-05-23 13:42:59 +000090 Worker = std::thread([this]() {
Ilya Biryukov38d79772017-05-16 09:38:59 +000091 while (true) {
Ilya Biryukov02d58702017-08-01 15:51:38 +000092 std::future<void> Request;
Ilya Biryukov38d79772017-05-16 09:38:59 +000093
94 // Pick request from the queue
95 {
96 std::unique_lock<std::mutex> Lock(Mutex);
97 // Wait for more requests.
98 RequestCV.wait(Lock, [this] { return !RequestQueue.empty() || Done; });
99 if (Done)
100 return;
101
102 assert(!RequestQueue.empty() && "RequestQueue was empty");
103
Ilya Biryukovf01af682017-05-23 13:42:59 +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();
Ilya Biryukov38d79772017-05-16 09:38:59 +0000110 } // unlock Mutex
111
Ilya Biryukov02d58702017-08-01 15:51:38 +0000112 Request.get();
Ilya Biryukov38d79772017-05-16 09:38:59 +0000113 }
114 });
115}
116
117ClangdScheduler::~ClangdScheduler() {
118 if (RunSynchronously)
119 return; // no worker thread is running in that case
120
121 {
122 std::lock_guard<std::mutex> Lock(Mutex);
123 // Wake up the worker thread
124 Done = true;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000125 } // unlock Mutex
Ilya Biryukovf01af682017-05-23 13:42:59 +0000126 RequestCV.notify_one();
Ilya Biryukov38d79772017-05-16 09:38:59 +0000127 Worker.join();
128}
129
Ilya Biryukov103c9512017-06-13 15:59:43 +0000130ClangdServer::ClangdServer(GlobalCompilationDatabase &CDB,
131 DiagnosticsConsumer &DiagConsumer,
132 FileSystemProvider &FSProvider,
Ilya Biryukova46f7a92017-06-28 10:34:50 +0000133 bool RunSynchronously,
134 llvm::Optional<StringRef> ResourceDir)
Ilya Biryukov103c9512017-06-13 15:59:43 +0000135 : CDB(CDB), DiagConsumer(DiagConsumer), FSProvider(FSProvider),
Ilya Biryukova46f7a92017-06-28 10:34:50 +0000136 ResourceDir(ResourceDir ? ResourceDir->str() : getStandardResourceDir()),
Ilya Biryukov38d79772017-05-16 09:38:59 +0000137 PCHs(std::make_shared<PCHContainerOperations>()),
Ilya Biryukovf01af682017-05-23 13:42:59 +0000138 WorkScheduler(RunSynchronously) {}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000139
Ilya Biryukov02d58702017-08-01 15:51:38 +0000140std::future<void> ClangdServer::addDocument(PathRef File, StringRef Contents) {
Ilya Biryukovf01af682017-05-23 13:42:59 +0000141 DocVersion Version = DraftMgr.updateDraft(File, Contents);
Ilya Biryukovf01af682017-05-23 13:42:59 +0000142
Ilya Biryukov02d58702017-08-01 15:51:38 +0000143 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
144 std::shared_ptr<CppFile> Resources =
145 Units.getOrCreateFile(File, ResourceDir, CDB, PCHs, TaggedFS.Value);
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000146 return scheduleReparseAndDiags(File, VersionedDraft{Version, Contents.str()},
147 std::move(Resources), std::move(TaggedFS));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000148}
149
Ilya Biryukov02d58702017-08-01 15:51:38 +0000150std::future<void> ClangdServer::removeDocument(PathRef File) {
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000151 DraftMgr.removeDraft(File);
152 std::shared_ptr<CppFile> Resources = Units.removeIfPresent(File);
153 return scheduleCancelRebuild(std::move(Resources));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000154}
155
Ilya Biryukov02d58702017-08-01 15:51:38 +0000156std::future<void> ClangdServer::forceReparse(PathRef File) {
Ilya Biryukov0f62ed22017-05-26 12:26:51 +0000157 // The addDocument schedules the reparse even if the contents of the file
158 // never changed, so we just call it here.
Ilya Biryukov02d58702017-08-01 15:51:38 +0000159 return addDocument(File, getDocument(File));
Ilya Biryukov0f62ed22017-05-26 12:26:51 +0000160}
161
Ilya Biryukov0e27ce42017-06-13 14:15:56 +0000162Tagged<std::vector<CompletionItem>>
163ClangdServer::codeComplete(PathRef File, Position Pos,
Ilya Biryukoved99e4c2017-07-31 17:09:29 +0000164 llvm::Optional<StringRef> OverridenContents,
165 IntrusiveRefCntPtr<vfs::FileSystem> *UsedFS) {
Ilya Biryukov0e27ce42017-06-13 14:15:56 +0000166 std::string DraftStorage;
167 if (!OverridenContents) {
168 auto FileContents = DraftMgr.getDraft(File);
169 assert(FileContents.Draft &&
170 "codeComplete is called for non-added document");
171
172 DraftStorage = std::move(*FileContents.Draft);
173 OverridenContents = DraftStorage;
174 }
Ilya Biryukov38d79772017-05-16 09:38:59 +0000175
Ilya Biryukovaf0c04b2017-06-14 09:46:44 +0000176 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
Ilya Biryukoved99e4c2017-07-31 17:09:29 +0000177 if (UsedFS)
178 *UsedFS = TaggedFS.Value;
179
Ilya Biryukov02d58702017-08-01 15:51:38 +0000180 std::shared_ptr<CppFile> Resources = Units.getFile(File);
181 assert(Resources && "Calling completion on non-added file");
182
183 auto Preamble = Resources->getPossiblyStalePreamble();
184 std::vector<CompletionItem> Result =
185 clangd::codeComplete(File, Resources->getCompileCommand(),
186 Preamble ? &Preamble->Preamble : nullptr,
187 *OverridenContents, Pos, TaggedFS.Value, PCHs);
Ilya Biryukov22602992017-05-30 15:11:02 +0000188 return make_tagged(std::move(Result), TaggedFS.Tag);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000189}
Ilya Biryukovf01af682017-05-23 13:42:59 +0000190
Ilya Biryukovafb55542017-05-16 14:40:30 +0000191std::vector<tooling::Replacement> ClangdServer::formatRange(PathRef File,
192 Range Rng) {
193 std::string Code = getDocument(File);
194
195 size_t Begin = positionToOffset(Code, Rng.start);
196 size_t Len = positionToOffset(Code, Rng.end) - Begin;
197 return formatCode(Code, File, {tooling::Range(Begin, Len)});
198}
199
200std::vector<tooling::Replacement> ClangdServer::formatFile(PathRef File) {
201 // Format everything.
202 std::string Code = getDocument(File);
203 return formatCode(Code, File, {tooling::Range(0, Code.size())});
204}
205
206std::vector<tooling::Replacement> ClangdServer::formatOnType(PathRef File,
207 Position Pos) {
208 // Look for the previous opening brace from the character position and
209 // format starting from there.
210 std::string Code = getDocument(File);
211 size_t CursorPos = positionToOffset(Code, Pos);
212 size_t PreviousLBracePos = StringRef(Code).find_last_of('{', CursorPos);
213 if (PreviousLBracePos == StringRef::npos)
214 PreviousLBracePos = CursorPos;
215 size_t Len = 1 + CursorPos - PreviousLBracePos;
216
217 return formatCode(Code, File, {tooling::Range(PreviousLBracePos, Len)});
218}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000219
220std::string ClangdServer::getDocument(PathRef File) {
221 auto draft = DraftMgr.getDraft(File);
222 assert(draft.Draft && "File is not tracked, cannot get contents");
223 return *draft.Draft;
224}
225
Ilya Biryukovf01af682017-05-23 13:42:59 +0000226std::string ClangdServer::dumpAST(PathRef File) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000227 std::shared_ptr<CppFile> Resources = Units.getFile(File);
228 assert(Resources && "dumpAST is called for non-added document");
Ilya Biryukov38d79772017-05-16 09:38:59 +0000229
Ilya Biryukov02d58702017-08-01 15:51:38 +0000230 std::string Result;
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +0000231 Resources->getAST().get()->runUnderLock([&Result](ParsedAST *AST) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000232 llvm::raw_string_ostream ResultOS(Result);
233 if (AST) {
234 clangd::dumpAST(*AST, ResultOS);
235 } else {
236 ResultOS << "<no-ast>";
237 }
238 ResultOS.flush();
Ilya Biryukovf01af682017-05-23 13:42:59 +0000239 });
Ilya Biryukov02d58702017-08-01 15:51:38 +0000240 return Result;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000241}
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000242
Ilya Biryukov02d58702017-08-01 15:51:38 +0000243Tagged<std::vector<Location>> ClangdServer::findDefinitions(PathRef File,
244 Position Pos) {
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000245 auto FileContents = DraftMgr.getDraft(File);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000246 assert(FileContents.Draft &&
247 "findDefinitions is called for non-added document");
248
249 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
250
251 std::shared_ptr<CppFile> Resources = Units.getFile(File);
252 assert(Resources && "Calling findDefinitions on non-added file");
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000253
254 std::vector<Location> Result;
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +0000255 Resources->getAST().get()->runUnderLock([Pos, &Result](ParsedAST *AST) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000256 if (!AST)
257 return;
258 Result = clangd::findDefinitions(*AST, Pos);
259 });
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000260 return make_tagged(std::move(Result), TaggedFS.Tag);
261}
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000262
263std::future<void> ClangdServer::scheduleReparseAndDiags(
264 PathRef File, VersionedDraft Contents, std::shared_ptr<CppFile> Resources,
265 Tagged<IntrusiveRefCntPtr<vfs::FileSystem>> TaggedFS) {
266
267 assert(Contents.Draft && "Draft must have contents");
268 std::future<llvm::Optional<std::vector<DiagWithFixIts>>> DeferredRebuild =
269 Resources->deferRebuild(*Contents.Draft, TaggedFS.Value);
270 std::promise<void> DonePromise;
271 std::future<void> DoneFuture = DonePromise.get_future();
272
273 DocVersion Version = Contents.Version;
274 Path FileStr = File;
275 VFSTag Tag = TaggedFS.Tag;
276 auto ReparseAndPublishDiags =
277 [this, FileStr, Version,
278 Tag](std::future<llvm::Optional<std::vector<DiagWithFixIts>>>
279 DeferredRebuild,
280 std::promise<void> DonePromise) -> void {
281 FulfillPromiseGuard Guard(DonePromise);
282
283 auto CurrentVersion = DraftMgr.getVersion(FileStr);
284 if (CurrentVersion != Version)
285 return; // This request is outdated
286
287 auto Diags = DeferredRebuild.get();
288 if (!Diags)
289 return; // A new reparse was requested before this one completed.
290 DiagConsumer.onDiagnosticsReady(FileStr,
291 make_tagged(std::move(*Diags), Tag));
292 };
293
294 WorkScheduler.addToFront(std::move(ReparseAndPublishDiags),
295 std::move(DeferredRebuild), std::move(DonePromise));
296 return DoneFuture;
297}
298
299std::future<void>
300ClangdServer::scheduleCancelRebuild(std::shared_ptr<CppFile> Resources) {
301 std::promise<void> DonePromise;
302 std::future<void> DoneFuture = DonePromise.get_future();
303 if (!Resources) {
304 // No need to schedule any cleanup.
305 DonePromise.set_value();
306 return DoneFuture;
307 }
308
309 std::future<void> DeferredCancel = Resources->deferCancelRebuild();
310 auto CancelReparses = [Resources](std::promise<void> DonePromise,
311 std::future<void> DeferredCancel) {
312 FulfillPromiseGuard Guard(DonePromise);
313 DeferredCancel.get();
314 };
315 WorkScheduler.addToFront(std::move(CancelReparses), std::move(DonePromise),
316 std::move(DeferredCancel));
317 return DoneFuture;
318}