blob: 73c1ae548f4efebe8e0a8b4a20399aac49540788 [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
26std::vector<tooling::Replacement> formatCode(StringRef Code, StringRef Filename,
27 ArrayRef<tooling::Range> Ranges) {
28 // Call clang-format.
29 // FIXME: Don't ignore style.
30 format::FormatStyle Style = format::getLLVMStyle();
31 auto Result = format::reformat(Style, Code, Ranges, Filename);
32
33 return std::vector<tooling::Replacement>(Result.begin(), Result.end());
34}
35
36} // namespace
37
38size_t clangd::positionToOffset(StringRef Code, Position P) {
39 size_t Offset = 0;
40 for (int I = 0; I != P.line; ++I) {
41 // FIXME: \r\n
42 // FIXME: UTF-8
43 size_t F = Code.find('\n', Offset);
44 if (F == StringRef::npos)
45 return 0; // FIXME: Is this reasonable?
46 Offset = F + 1;
47 }
48 return (Offset == 0 ? 0 : (Offset - 1)) + P.character;
49}
50
51/// Turn an offset in Code into a [line, column] pair.
52Position clangd::offsetToPosition(StringRef Code, size_t Offset) {
53 StringRef JustBefore = Code.substr(0, Offset);
54 // FIXME: \r\n
55 // FIXME: UTF-8
56 int Lines = JustBefore.count('\n');
57 int Cols = JustBefore.size() - JustBefore.rfind('\n') - 1;
58 return {Lines, Cols};
59}
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 Biryukovf01af682017-05-23 13:42:59 +000066ClangdScheduler::ClangdScheduler(bool RunSynchronously)
Ilya Biryukov38d79772017-05-16 09:38:59 +000067 : RunSynchronously(RunSynchronously) {
68 if (RunSynchronously) {
69 // Don't start the worker thread if we're running synchronously
70 return;
71 }
72
73 // Initialize Worker in ctor body, rather than init list to avoid potentially
74 // using not-yet-initialized members
Ilya Biryukovf01af682017-05-23 13:42:59 +000075 Worker = std::thread([this]() {
Ilya Biryukov38d79772017-05-16 09:38:59 +000076 while (true) {
Ilya Biryukovf01af682017-05-23 13:42:59 +000077 std::function<void()> Request;
Ilya Biryukov38d79772017-05-16 09:38:59 +000078
79 // Pick request from the queue
80 {
81 std::unique_lock<std::mutex> Lock(Mutex);
82 // Wait for more requests.
83 RequestCV.wait(Lock, [this] { return !RequestQueue.empty() || Done; });
84 if (Done)
85 return;
86
87 assert(!RequestQueue.empty() && "RequestQueue was empty");
88
Ilya Biryukovf01af682017-05-23 13:42:59 +000089 // We process requests starting from the front of the queue. Users of
90 // ClangdScheduler have a way to prioritise their requests by putting
91 // them to the either side of the queue (using either addToEnd or
92 // addToFront).
93 Request = std::move(RequestQueue.front());
94 RequestQueue.pop_front();
Ilya Biryukov38d79772017-05-16 09:38:59 +000095 } // unlock Mutex
96
Ilya Biryukovf01af682017-05-23 13:42:59 +000097 Request();
Ilya Biryukov38d79772017-05-16 09:38:59 +000098 }
99 });
100}
101
102ClangdScheduler::~ClangdScheduler() {
103 if (RunSynchronously)
104 return; // no worker thread is running in that case
105
106 {
107 std::lock_guard<std::mutex> Lock(Mutex);
108 // Wake up the worker thread
109 Done = true;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000110 } // unlock Mutex
Ilya Biryukovf01af682017-05-23 13:42:59 +0000111 RequestCV.notify_one();
Ilya Biryukov38d79772017-05-16 09:38:59 +0000112 Worker.join();
113}
114
Ilya Biryukovf01af682017-05-23 13:42:59 +0000115void ClangdScheduler::addToFront(std::function<void()> Request) {
Ilya Biryukov38d79772017-05-16 09:38:59 +0000116 if (RunSynchronously) {
Ilya Biryukovf01af682017-05-23 13:42:59 +0000117 Request();
Ilya Biryukov38d79772017-05-16 09:38:59 +0000118 return;
119 }
120
Ilya Biryukovf01af682017-05-23 13:42:59 +0000121 {
122 std::lock_guard<std::mutex> Lock(Mutex);
123 RequestQueue.push_front(Request);
124 }
125 RequestCV.notify_one();
126}
127
128void ClangdScheduler::addToEnd(std::function<void()> Request) {
129 if (RunSynchronously) {
130 Request();
131 return;
132 }
133
134 {
135 std::lock_guard<std::mutex> Lock(Mutex);
136 RequestQueue.push_back(Request);
137 }
Ilya Biryukov38d79772017-05-16 09:38:59 +0000138 RequestCV.notify_one();
139}
140
Ilya Biryukov103c9512017-06-13 15:59:43 +0000141ClangdServer::ClangdServer(GlobalCompilationDatabase &CDB,
142 DiagnosticsConsumer &DiagConsumer,
143 FileSystemProvider &FSProvider,
Ilya Biryukov38d79772017-05-16 09:38:59 +0000144 bool RunSynchronously)
Ilya Biryukov103c9512017-06-13 15:59:43 +0000145 : CDB(CDB), DiagConsumer(DiagConsumer), FSProvider(FSProvider),
Ilya Biryukov38d79772017-05-16 09:38:59 +0000146 PCHs(std::make_shared<PCHContainerOperations>()),
Ilya Biryukovf01af682017-05-23 13:42:59 +0000147 WorkScheduler(RunSynchronously) {}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000148
149void ClangdServer::addDocument(PathRef File, StringRef Contents) {
Ilya Biryukovf01af682017-05-23 13:42:59 +0000150 DocVersion Version = DraftMgr.updateDraft(File, Contents);
151 Path FileStr = File;
152 WorkScheduler.addToFront([this, FileStr, Version]() {
153 auto FileContents = DraftMgr.getDraft(FileStr);
154 if (FileContents.Version != Version)
155 return; // This request is outdated, do nothing
156
157 assert(FileContents.Draft &&
158 "No contents inside a file that was scheduled for reparse");
Ilya Biryukovaf0c04b2017-06-14 09:46:44 +0000159 auto TaggedFS = FSProvider.getTaggedFileSystem(FileStr);
Ilya Biryukov22602992017-05-30 15:11:02 +0000160 Units.runOnUnit(
Ilya Biryukov103c9512017-06-13 15:59:43 +0000161 FileStr, *FileContents.Draft, CDB, PCHs, TaggedFS.Value,
Ilya Biryukov22602992017-05-30 15:11:02 +0000162 [&](ClangdUnit const &Unit) {
Ilya Biryukov103c9512017-06-13 15:59:43 +0000163 DiagConsumer.onDiagnosticsReady(
Ilya Biryukov22602992017-05-30 15:11:02 +0000164 FileStr, make_tagged(Unit.getLocalDiagnostics(), TaggedFS.Tag));
165 });
Ilya Biryukovf01af682017-05-23 13:42:59 +0000166 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000167}
168
169void ClangdServer::removeDocument(PathRef File) {
Ilya Biryukovf01af682017-05-23 13:42:59 +0000170 auto Version = DraftMgr.removeDraft(File);
171 Path FileStr = File;
172 WorkScheduler.addToFront([this, FileStr, Version]() {
173 if (Version != DraftMgr.getVersion(FileStr))
174 return; // This request is outdated, do nothing
175
176 Units.removeUnitIfPresent(FileStr);
177 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000178}
179
Ilya Biryukov0f62ed22017-05-26 12:26:51 +0000180void ClangdServer::forceReparse(PathRef File) {
181 // The addDocument schedules the reparse even if the contents of the file
182 // never changed, so we just call it here.
183 addDocument(File, getDocument(File));
184}
185
Ilya Biryukov0e27ce42017-06-13 14:15:56 +0000186Tagged<std::vector<CompletionItem>>
187ClangdServer::codeComplete(PathRef File, Position Pos,
188 llvm::Optional<StringRef> OverridenContents) {
189 std::string DraftStorage;
190 if (!OverridenContents) {
191 auto FileContents = DraftMgr.getDraft(File);
192 assert(FileContents.Draft &&
193 "codeComplete is called for non-added document");
194
195 DraftStorage = std::move(*FileContents.Draft);
196 OverridenContents = DraftStorage;
197 }
Ilya Biryukov38d79772017-05-16 09:38:59 +0000198
199 std::vector<CompletionItem> Result;
Ilya Biryukovaf0c04b2017-06-14 09:46:44 +0000200 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
Ilya Biryukov0e27ce42017-06-13 14:15:56 +0000201 // It would be nice to use runOnUnitWithoutReparse here, but we can't
202 // guarantee the correctness of code completion cache here if we don't do the
203 // reparse.
Ilya Biryukov103c9512017-06-13 15:59:43 +0000204 Units.runOnUnit(File, *OverridenContents, CDB, PCHs, TaggedFS.Value,
Ilya Biryukov0e27ce42017-06-13 14:15:56 +0000205 [&](ClangdUnit &Unit) {
206 Result = Unit.codeComplete(*OverridenContents, Pos,
207 TaggedFS.Value);
208 });
Ilya Biryukov22602992017-05-30 15:11:02 +0000209 return make_tagged(std::move(Result), TaggedFS.Tag);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000210}
Ilya Biryukovf01af682017-05-23 13:42:59 +0000211
Ilya Biryukovafb55542017-05-16 14:40:30 +0000212std::vector<tooling::Replacement> ClangdServer::formatRange(PathRef File,
213 Range Rng) {
214 std::string Code = getDocument(File);
215
216 size_t Begin = positionToOffset(Code, Rng.start);
217 size_t Len = positionToOffset(Code, Rng.end) - Begin;
218 return formatCode(Code, File, {tooling::Range(Begin, Len)});
219}
220
221std::vector<tooling::Replacement> ClangdServer::formatFile(PathRef File) {
222 // Format everything.
223 std::string Code = getDocument(File);
224 return formatCode(Code, File, {tooling::Range(0, Code.size())});
225}
226
227std::vector<tooling::Replacement> ClangdServer::formatOnType(PathRef File,
228 Position Pos) {
229 // Look for the previous opening brace from the character position and
230 // format starting from there.
231 std::string Code = getDocument(File);
232 size_t CursorPos = positionToOffset(Code, Pos);
233 size_t PreviousLBracePos = StringRef(Code).find_last_of('{', CursorPos);
234 if (PreviousLBracePos == StringRef::npos)
235 PreviousLBracePos = CursorPos;
236 size_t Len = 1 + CursorPos - PreviousLBracePos;
237
238 return formatCode(Code, File, {tooling::Range(PreviousLBracePos, Len)});
239}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000240
241std::string ClangdServer::getDocument(PathRef File) {
242 auto draft = DraftMgr.getDraft(File);
243 assert(draft.Draft && "File is not tracked, cannot get contents");
244 return *draft.Draft;
245}
246
Ilya Biryukovf01af682017-05-23 13:42:59 +0000247std::string ClangdServer::dumpAST(PathRef File) {
248 std::promise<std::string> DumpPromise;
249 auto DumpFuture = DumpPromise.get_future();
250 auto Version = DraftMgr.getVersion(File);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000251
Ilya Biryukovf01af682017-05-23 13:42:59 +0000252 WorkScheduler.addToEnd([this, &DumpPromise, File, Version]() {
253 assert(DraftMgr.getVersion(File) == Version && "Version has changed");
Ilya Biryukov38d79772017-05-16 09:38:59 +0000254
Ilya Biryukovf01af682017-05-23 13:42:59 +0000255 Units.runOnExistingUnit(File, [&DumpPromise](ClangdUnit &Unit) {
256 std::string Result;
257
258 llvm::raw_string_ostream ResultOS(Result);
259 Unit.dumpAST(ResultOS);
260 ResultOS.flush();
261
262 DumpPromise.set_value(std::move(Result));
263 });
264 });
265 return DumpFuture.get();
Ilya Biryukov38d79772017-05-16 09:38:59 +0000266}