blob: 459b6a6421771879d1ed26088bf931e94f8af802 [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>>
62RealFileSystemProvider::getTaggedFileSystem() {
63 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
141ClangdServer::ClangdServer(std::unique_ptr<GlobalCompilationDatabase> CDB,
142 std::unique_ptr<DiagnosticsConsumer> DiagConsumer,
Ilya Biryukov0f62ed22017-05-26 12:26:51 +0000143 std::unique_ptr<FileSystemProvider> FSProvider,
Ilya Biryukov38d79772017-05-16 09:38:59 +0000144 bool RunSynchronously)
145 : CDB(std::move(CDB)), DiagConsumer(std::move(DiagConsumer)),
Ilya Biryukov0f62ed22017-05-26 12:26:51 +0000146 FSProvider(std::move(FSProvider)),
Ilya Biryukov38d79772017-05-16 09:38:59 +0000147 PCHs(std::make_shared<PCHContainerOperations>()),
Ilya Biryukovf01af682017-05-23 13:42:59 +0000148 WorkScheduler(RunSynchronously) {}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000149
150void ClangdServer::addDocument(PathRef File, StringRef Contents) {
Ilya Biryukovf01af682017-05-23 13:42:59 +0000151 DocVersion Version = DraftMgr.updateDraft(File, Contents);
152 Path FileStr = File;
153 WorkScheduler.addToFront([this, FileStr, Version]() {
154 auto FileContents = DraftMgr.getDraft(FileStr);
155 if (FileContents.Version != Version)
156 return; // This request is outdated, do nothing
157
158 assert(FileContents.Draft &&
159 "No contents inside a file that was scheduled for reparse");
Ilya Biryukov22602992017-05-30 15:11:02 +0000160 auto TaggedFS = FSProvider->getTaggedFileSystem();
161 Units.runOnUnit(
162 FileStr, *FileContents.Draft, *CDB, PCHs, TaggedFS.Value,
163 [&](ClangdUnit const &Unit) {
164 DiagConsumer->onDiagnosticsReady(
165 FileStr, make_tagged(Unit.getLocalDiagnostics(), TaggedFS.Tag));
166 });
Ilya Biryukovf01af682017-05-23 13:42:59 +0000167 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000168}
169
170void ClangdServer::removeDocument(PathRef File) {
Ilya Biryukovf01af682017-05-23 13:42:59 +0000171 auto Version = DraftMgr.removeDraft(File);
172 Path FileStr = File;
173 WorkScheduler.addToFront([this, FileStr, Version]() {
174 if (Version != DraftMgr.getVersion(FileStr))
175 return; // This request is outdated, do nothing
176
177 Units.removeUnitIfPresent(FileStr);
178 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000179}
180
Ilya Biryukov0f62ed22017-05-26 12:26:51 +0000181void ClangdServer::forceReparse(PathRef File) {
182 // The addDocument schedules the reparse even if the contents of the file
183 // never changed, so we just call it here.
184 addDocument(File, getDocument(File));
185}
186
Ilya Biryukov22602992017-05-30 15:11:02 +0000187Tagged<std::vector<CompletionItem>> ClangdServer::codeComplete(PathRef File,
188 Position Pos) {
Ilya Biryukov38d79772017-05-16 09:38:59 +0000189 auto FileContents = DraftMgr.getDraft(File);
190 assert(FileContents.Draft && "codeComplete is called for non-added document");
191
192 std::vector<CompletionItem> Result;
Ilya Biryukov22602992017-05-30 15:11:02 +0000193 auto TaggedFS = FSProvider->getTaggedFileSystem();
Ilya Biryukov38d79772017-05-16 09:38:59 +0000194 Units.runOnUnitWithoutReparse(
Ilya Biryukov22602992017-05-30 15:11:02 +0000195 File, *FileContents.Draft, *CDB, PCHs, TaggedFS.Value, [&](ClangdUnit &Unit) {
196 Result = Unit.codeComplete(*FileContents.Draft, Pos, TaggedFS.Value);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000197 });
Ilya Biryukov22602992017-05-30 15:11:02 +0000198 return make_tagged(std::move(Result), TaggedFS.Tag);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000199}
Ilya Biryukovf01af682017-05-23 13:42:59 +0000200
Ilya Biryukovafb55542017-05-16 14:40:30 +0000201std::vector<tooling::Replacement> ClangdServer::formatRange(PathRef File,
202 Range Rng) {
203 std::string Code = getDocument(File);
204
205 size_t Begin = positionToOffset(Code, Rng.start);
206 size_t Len = positionToOffset(Code, Rng.end) - Begin;
207 return formatCode(Code, File, {tooling::Range(Begin, Len)});
208}
209
210std::vector<tooling::Replacement> ClangdServer::formatFile(PathRef File) {
211 // Format everything.
212 std::string Code = getDocument(File);
213 return formatCode(Code, File, {tooling::Range(0, Code.size())});
214}
215
216std::vector<tooling::Replacement> ClangdServer::formatOnType(PathRef File,
217 Position Pos) {
218 // Look for the previous opening brace from the character position and
219 // format starting from there.
220 std::string Code = getDocument(File);
221 size_t CursorPos = positionToOffset(Code, Pos);
222 size_t PreviousLBracePos = StringRef(Code).find_last_of('{', CursorPos);
223 if (PreviousLBracePos == StringRef::npos)
224 PreviousLBracePos = CursorPos;
225 size_t Len = 1 + CursorPos - PreviousLBracePos;
226
227 return formatCode(Code, File, {tooling::Range(PreviousLBracePos, Len)});
228}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000229
230std::string ClangdServer::getDocument(PathRef File) {
231 auto draft = DraftMgr.getDraft(File);
232 assert(draft.Draft && "File is not tracked, cannot get contents");
233 return *draft.Draft;
234}
235
Ilya Biryukovf01af682017-05-23 13:42:59 +0000236std::string ClangdServer::dumpAST(PathRef File) {
237 std::promise<std::string> DumpPromise;
238 auto DumpFuture = DumpPromise.get_future();
239 auto Version = DraftMgr.getVersion(File);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000240
Ilya Biryukovf01af682017-05-23 13:42:59 +0000241 WorkScheduler.addToEnd([this, &DumpPromise, File, Version]() {
242 assert(DraftMgr.getVersion(File) == Version && "Version has changed");
Ilya Biryukov38d79772017-05-16 09:38:59 +0000243
Ilya Biryukovf01af682017-05-23 13:42:59 +0000244 Units.runOnExistingUnit(File, [&DumpPromise](ClangdUnit &Unit) {
245 std::string Result;
246
247 llvm::raw_string_ostream ResultOS(Result);
248 Unit.dumpAST(ResultOS);
249 ResultOS.flush();
250
251 DumpPromise.set_value(std::move(Result));
252 });
253 });
254 return DumpFuture.get();
Ilya Biryukov38d79772017-05-16 09:38:59 +0000255}