blob: c15d5544dcd2828711d5609c719e930e6c85fb44 [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);
146
147 std::future<llvm::Optional<std::vector<DiagWithFixIts>>> DeferredRebuild =
148 Resources->deferRebuild(Contents, TaggedFS.Value);
149 std::promise<void> DonePromise;
150 std::future<void> DoneFuture = DonePromise.get_future();
151
152 Path FileStr = File;
153 VFSTag Tag = TaggedFS.Tag;
154 auto ReparseAndPublishDiags =
155 [this, FileStr, Version,
156 Tag](std::future<llvm::Optional<std::vector<DiagWithFixIts>>>
157 DeferredRebuild,
158 std::promise<void> DonePromise) -> void {
159 FulfillPromiseGuard Guard(DonePromise);
160
161 auto CurrentVersion = DraftMgr.getVersion(FileStr);
162 if (CurrentVersion != Version)
163 return; // This request is outdated
164
165 auto Diags = DeferredRebuild.get();
166 if (!Diags)
167 return; // A new reparse was requested before this one completed.
168 DiagConsumer.onDiagnosticsReady(FileStr,
169 make_tagged(std::move(*Diags), Tag));
170 };
171
172 WorkScheduler.addToFront(std::move(ReparseAndPublishDiags),
173 std::move(DeferredRebuild), std::move(DonePromise));
174 return DoneFuture;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000175}
176
Ilya Biryukov02d58702017-08-01 15:51:38 +0000177std::future<void> ClangdServer::removeDocument(PathRef File) {
Ilya Biryukovf01af682017-05-23 13:42:59 +0000178 auto Version = DraftMgr.removeDraft(File);
179 Path FileStr = File;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000180
181 std::promise<void> DonePromise;
182 std::future<void> DoneFuture = DonePromise.get_future();
183
184 auto RemoveDocFromCollection = [this, FileStr,
185 Version](std::promise<void> DonePromise) {
186 FulfillPromiseGuard Guard(DonePromise);
187
Ilya Biryukovf01af682017-05-23 13:42:59 +0000188 if (Version != DraftMgr.getVersion(FileStr))
189 return; // This request is outdated, do nothing
190
Ilya Biryukov02d58702017-08-01 15:51:38 +0000191 std::shared_ptr<CppFile> File = Units.removeIfPresent(FileStr);
192 if (!File)
193 return;
194 // Cancel all ongoing rebuilds, so that we don't do extra work before
195 // deleting this file.
196 File->cancelRebuilds();
197 };
198 WorkScheduler.addToFront(std::move(RemoveDocFromCollection),
199 std::move(DonePromise));
200 return DoneFuture;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000201}
202
Ilya Biryukov02d58702017-08-01 15:51:38 +0000203std::future<void> ClangdServer::forceReparse(PathRef File) {
Ilya Biryukov0f62ed22017-05-26 12:26:51 +0000204 // The addDocument schedules the reparse even if the contents of the file
205 // never changed, so we just call it here.
Ilya Biryukov02d58702017-08-01 15:51:38 +0000206 return addDocument(File, getDocument(File));
Ilya Biryukov0f62ed22017-05-26 12:26:51 +0000207}
208
Ilya Biryukov0e27ce42017-06-13 14:15:56 +0000209Tagged<std::vector<CompletionItem>>
210ClangdServer::codeComplete(PathRef File, Position Pos,
Ilya Biryukoved99e4c2017-07-31 17:09:29 +0000211 llvm::Optional<StringRef> OverridenContents,
212 IntrusiveRefCntPtr<vfs::FileSystem> *UsedFS) {
Ilya Biryukov0e27ce42017-06-13 14:15:56 +0000213 std::string DraftStorage;
214 if (!OverridenContents) {
215 auto FileContents = DraftMgr.getDraft(File);
216 assert(FileContents.Draft &&
217 "codeComplete is called for non-added document");
218
219 DraftStorage = std::move(*FileContents.Draft);
220 OverridenContents = DraftStorage;
221 }
Ilya Biryukov38d79772017-05-16 09:38:59 +0000222
Ilya Biryukovaf0c04b2017-06-14 09:46:44 +0000223 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
Ilya Biryukoved99e4c2017-07-31 17:09:29 +0000224 if (UsedFS)
225 *UsedFS = TaggedFS.Value;
226
Ilya Biryukov02d58702017-08-01 15:51:38 +0000227 std::shared_ptr<CppFile> Resources = Units.getFile(File);
228 assert(Resources && "Calling completion on non-added file");
229
230 auto Preamble = Resources->getPossiblyStalePreamble();
231 std::vector<CompletionItem> Result =
232 clangd::codeComplete(File, Resources->getCompileCommand(),
233 Preamble ? &Preamble->Preamble : nullptr,
234 *OverridenContents, Pos, TaggedFS.Value, PCHs);
Ilya Biryukov22602992017-05-30 15:11:02 +0000235 return make_tagged(std::move(Result), TaggedFS.Tag);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000236}
Ilya Biryukovf01af682017-05-23 13:42:59 +0000237
Ilya Biryukovafb55542017-05-16 14:40:30 +0000238std::vector<tooling::Replacement> ClangdServer::formatRange(PathRef File,
239 Range Rng) {
240 std::string Code = getDocument(File);
241
242 size_t Begin = positionToOffset(Code, Rng.start);
243 size_t Len = positionToOffset(Code, Rng.end) - Begin;
244 return formatCode(Code, File, {tooling::Range(Begin, Len)});
245}
246
247std::vector<tooling::Replacement> ClangdServer::formatFile(PathRef File) {
248 // Format everything.
249 std::string Code = getDocument(File);
250 return formatCode(Code, File, {tooling::Range(0, Code.size())});
251}
252
253std::vector<tooling::Replacement> ClangdServer::formatOnType(PathRef File,
254 Position Pos) {
255 // Look for the previous opening brace from the character position and
256 // format starting from there.
257 std::string Code = getDocument(File);
258 size_t CursorPos = positionToOffset(Code, Pos);
259 size_t PreviousLBracePos = StringRef(Code).find_last_of('{', CursorPos);
260 if (PreviousLBracePos == StringRef::npos)
261 PreviousLBracePos = CursorPos;
262 size_t Len = 1 + CursorPos - PreviousLBracePos;
263
264 return formatCode(Code, File, {tooling::Range(PreviousLBracePos, Len)});
265}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000266
267std::string ClangdServer::getDocument(PathRef File) {
268 auto draft = DraftMgr.getDraft(File);
269 assert(draft.Draft && "File is not tracked, cannot get contents");
270 return *draft.Draft;
271}
272
Ilya Biryukovf01af682017-05-23 13:42:59 +0000273std::string ClangdServer::dumpAST(PathRef File) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000274 std::shared_ptr<CppFile> Resources = Units.getFile(File);
275 assert(Resources && "dumpAST is called for non-added document");
Ilya Biryukov38d79772017-05-16 09:38:59 +0000276
Ilya Biryukov02d58702017-08-01 15:51:38 +0000277 std::string Result;
278 Resources->getAST().get().runUnderLock([&Result](ParsedAST *AST) {
279 llvm::raw_string_ostream ResultOS(Result);
280 if (AST) {
281 clangd::dumpAST(*AST, ResultOS);
282 } else {
283 ResultOS << "<no-ast>";
284 }
285 ResultOS.flush();
Ilya Biryukovf01af682017-05-23 13:42:59 +0000286 });
Ilya Biryukov02d58702017-08-01 15:51:38 +0000287 return Result;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000288}
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000289
Ilya Biryukov02d58702017-08-01 15:51:38 +0000290Tagged<std::vector<Location>> ClangdServer::findDefinitions(PathRef File,
291 Position Pos) {
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000292 auto FileContents = DraftMgr.getDraft(File);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000293 assert(FileContents.Draft &&
294 "findDefinitions is called for non-added document");
295
296 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
297
298 std::shared_ptr<CppFile> Resources = Units.getFile(File);
299 assert(Resources && "Calling findDefinitions on non-added file");
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000300
301 std::vector<Location> Result;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000302 Resources->getAST().get().runUnderLock([Pos, &Result](ParsedAST *AST) {
303 if (!AST)
304 return;
305 Result = clangd::findDefinitions(*AST, Pos);
306 });
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000307 return make_tagged(std::move(Result), TaggedFS.Tag);
308}