blob: feadf71fabc9f66c9b4dd89d6d355c3d6e4ccfce [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 Biryukov0f62ed22017-05-26 12:26:51 +000061IntrusiveRefCntPtr<vfs::FileSystem> RealFileSystemProvider::getFileSystem() {
62 return vfs::getRealFileSystem();
63}
64
Ilya Biryukovf01af682017-05-23 13:42:59 +000065ClangdScheduler::ClangdScheduler(bool RunSynchronously)
Ilya Biryukov38d79772017-05-16 09:38:59 +000066 : RunSynchronously(RunSynchronously) {
67 if (RunSynchronously) {
68 // Don't start the worker thread if we're running synchronously
69 return;
70 }
71
72 // Initialize Worker in ctor body, rather than init list to avoid potentially
73 // using not-yet-initialized members
Ilya Biryukovf01af682017-05-23 13:42:59 +000074 Worker = std::thread([this]() {
Ilya Biryukov38d79772017-05-16 09:38:59 +000075 while (true) {
Ilya Biryukovf01af682017-05-23 13:42:59 +000076 std::function<void()> Request;
Ilya Biryukov38d79772017-05-16 09:38:59 +000077
78 // Pick request from the queue
79 {
80 std::unique_lock<std::mutex> Lock(Mutex);
81 // Wait for more requests.
82 RequestCV.wait(Lock, [this] { return !RequestQueue.empty() || Done; });
83 if (Done)
84 return;
85
86 assert(!RequestQueue.empty() && "RequestQueue was empty");
87
Ilya Biryukovf01af682017-05-23 13:42:59 +000088 // We process requests starting from the front of the queue. Users of
89 // ClangdScheduler have a way to prioritise their requests by putting
90 // them to the either side of the queue (using either addToEnd or
91 // addToFront).
92 Request = std::move(RequestQueue.front());
93 RequestQueue.pop_front();
Ilya Biryukov38d79772017-05-16 09:38:59 +000094 } // unlock Mutex
95
Ilya Biryukovf01af682017-05-23 13:42:59 +000096 Request();
Ilya Biryukov38d79772017-05-16 09:38:59 +000097 }
98 });
99}
100
101ClangdScheduler::~ClangdScheduler() {
102 if (RunSynchronously)
103 return; // no worker thread is running in that case
104
105 {
106 std::lock_guard<std::mutex> Lock(Mutex);
107 // Wake up the worker thread
108 Done = true;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000109 } // unlock Mutex
Ilya Biryukovf01af682017-05-23 13:42:59 +0000110 RequestCV.notify_one();
Ilya Biryukov38d79772017-05-16 09:38:59 +0000111 Worker.join();
112}
113
Ilya Biryukovf01af682017-05-23 13:42:59 +0000114void ClangdScheduler::addToFront(std::function<void()> Request) {
Ilya Biryukov38d79772017-05-16 09:38:59 +0000115 if (RunSynchronously) {
Ilya Biryukovf01af682017-05-23 13:42:59 +0000116 Request();
Ilya Biryukov38d79772017-05-16 09:38:59 +0000117 return;
118 }
119
Ilya Biryukovf01af682017-05-23 13:42:59 +0000120 {
121 std::lock_guard<std::mutex> Lock(Mutex);
122 RequestQueue.push_front(Request);
123 }
124 RequestCV.notify_one();
125}
126
127void ClangdScheduler::addToEnd(std::function<void()> Request) {
128 if (RunSynchronously) {
129 Request();
130 return;
131 }
132
133 {
134 std::lock_guard<std::mutex> Lock(Mutex);
135 RequestQueue.push_back(Request);
136 }
Ilya Biryukov38d79772017-05-16 09:38:59 +0000137 RequestCV.notify_one();
138}
139
140ClangdServer::ClangdServer(std::unique_ptr<GlobalCompilationDatabase> CDB,
141 std::unique_ptr<DiagnosticsConsumer> DiagConsumer,
Ilya Biryukov0f62ed22017-05-26 12:26:51 +0000142 std::unique_ptr<FileSystemProvider> FSProvider,
Ilya Biryukov38d79772017-05-16 09:38:59 +0000143 bool RunSynchronously)
144 : CDB(std::move(CDB)), DiagConsumer(std::move(DiagConsumer)),
Ilya Biryukov0f62ed22017-05-26 12:26:51 +0000145 FSProvider(std::move(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 Biryukov0f62ed22017-05-26 12:26:51 +0000159 Units.runOnUnit(FileStr, *FileContents.Draft, *CDB, PCHs,
160 FSProvider->getFileSystem(), [&](ClangdUnit const &Unit) {
161 DiagConsumer->onDiagnosticsReady(
162 FileStr, Unit.getLocalDiagnostics());
163 });
Ilya Biryukovf01af682017-05-23 13:42:59 +0000164 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000165}
166
167void ClangdServer::removeDocument(PathRef File) {
Ilya Biryukovf01af682017-05-23 13:42:59 +0000168 auto Version = DraftMgr.removeDraft(File);
169 Path FileStr = File;
170 WorkScheduler.addToFront([this, FileStr, Version]() {
171 if (Version != DraftMgr.getVersion(FileStr))
172 return; // This request is outdated, do nothing
173
174 Units.removeUnitIfPresent(FileStr);
175 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000176}
177
Ilya Biryukov0f62ed22017-05-26 12:26:51 +0000178void ClangdServer::forceReparse(PathRef File) {
179 // The addDocument schedules the reparse even if the contents of the file
180 // never changed, so we just call it here.
181 addDocument(File, getDocument(File));
182}
183
Ilya Biryukov38d79772017-05-16 09:38:59 +0000184std::vector<CompletionItem> ClangdServer::codeComplete(PathRef File,
185 Position Pos) {
186 auto FileContents = DraftMgr.getDraft(File);
187 assert(FileContents.Draft && "codeComplete is called for non-added document");
188
189 std::vector<CompletionItem> Result;
Ilya Biryukov0f62ed22017-05-26 12:26:51 +0000190 auto VFS = FSProvider->getFileSystem();
Ilya Biryukov38d79772017-05-16 09:38:59 +0000191 Units.runOnUnitWithoutReparse(
Ilya Biryukov0f62ed22017-05-26 12:26:51 +0000192 File, *FileContents.Draft, *CDB, PCHs, VFS, [&](ClangdUnit &Unit) {
193 Result = Unit.codeComplete(*FileContents.Draft, Pos, VFS);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000194 });
195 return Result;
196}
Ilya Biryukovf01af682017-05-23 13:42:59 +0000197
Ilya Biryukovafb55542017-05-16 14:40:30 +0000198std::vector<tooling::Replacement> ClangdServer::formatRange(PathRef File,
199 Range Rng) {
200 std::string Code = getDocument(File);
201
202 size_t Begin = positionToOffset(Code, Rng.start);
203 size_t Len = positionToOffset(Code, Rng.end) - Begin;
204 return formatCode(Code, File, {tooling::Range(Begin, Len)});
205}
206
207std::vector<tooling::Replacement> ClangdServer::formatFile(PathRef File) {
208 // Format everything.
209 std::string Code = getDocument(File);
210 return formatCode(Code, File, {tooling::Range(0, Code.size())});
211}
212
213std::vector<tooling::Replacement> ClangdServer::formatOnType(PathRef File,
214 Position Pos) {
215 // Look for the previous opening brace from the character position and
216 // format starting from there.
217 std::string Code = getDocument(File);
218 size_t CursorPos = positionToOffset(Code, Pos);
219 size_t PreviousLBracePos = StringRef(Code).find_last_of('{', CursorPos);
220 if (PreviousLBracePos == StringRef::npos)
221 PreviousLBracePos = CursorPos;
222 size_t Len = 1 + CursorPos - PreviousLBracePos;
223
224 return formatCode(Code, File, {tooling::Range(PreviousLBracePos, Len)});
225}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000226
227std::string ClangdServer::getDocument(PathRef File) {
228 auto draft = DraftMgr.getDraft(File);
229 assert(draft.Draft && "File is not tracked, cannot get contents");
230 return *draft.Draft;
231}
232
Ilya Biryukovf01af682017-05-23 13:42:59 +0000233std::string ClangdServer::dumpAST(PathRef File) {
234 std::promise<std::string> DumpPromise;
235 auto DumpFuture = DumpPromise.get_future();
236 auto Version = DraftMgr.getVersion(File);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000237
Ilya Biryukovf01af682017-05-23 13:42:59 +0000238 WorkScheduler.addToEnd([this, &DumpPromise, File, Version]() {
239 assert(DraftMgr.getVersion(File) == Version && "Version has changed");
Ilya Biryukov38d79772017-05-16 09:38:59 +0000240
Ilya Biryukovf01af682017-05-23 13:42:59 +0000241 Units.runOnExistingUnit(File, [&DumpPromise](ClangdUnit &Unit) {
242 std::string Result;
243
244 llvm::raw_string_ostream ResultOS(Result);
245 Unit.dumpAST(ResultOS);
246 ResultOS.flush();
247
248 DumpPromise.set_value(std::move(Result));
249 });
250 });
251 return DumpFuture.get();
Ilya Biryukov38d79772017-05-16 09:38:59 +0000252}