blob: 3a8d1c6dad1e5d7bc9c3d080095c2e91731a4d68 [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 Biryukovf01af682017-05-23 13:42:59 +000061ClangdScheduler::ClangdScheduler(bool RunSynchronously)
Ilya Biryukov38d79772017-05-16 09:38:59 +000062 : RunSynchronously(RunSynchronously) {
63 if (RunSynchronously) {
64 // Don't start the worker thread if we're running synchronously
65 return;
66 }
67
68 // Initialize Worker in ctor body, rather than init list to avoid potentially
69 // using not-yet-initialized members
Ilya Biryukovf01af682017-05-23 13:42:59 +000070 Worker = std::thread([this]() {
Ilya Biryukov38d79772017-05-16 09:38:59 +000071 while (true) {
Ilya Biryukovf01af682017-05-23 13:42:59 +000072 std::function<void()> Request;
Ilya Biryukov38d79772017-05-16 09:38:59 +000073
74 // Pick request from the queue
75 {
76 std::unique_lock<std::mutex> Lock(Mutex);
77 // Wait for more requests.
78 RequestCV.wait(Lock, [this] { return !RequestQueue.empty() || Done; });
79 if (Done)
80 return;
81
82 assert(!RequestQueue.empty() && "RequestQueue was empty");
83
Ilya Biryukovf01af682017-05-23 13:42:59 +000084 // We process requests starting from the front of the queue. Users of
85 // ClangdScheduler have a way to prioritise their requests by putting
86 // them to the either side of the queue (using either addToEnd or
87 // addToFront).
88 Request = std::move(RequestQueue.front());
89 RequestQueue.pop_front();
Ilya Biryukov38d79772017-05-16 09:38:59 +000090 } // unlock Mutex
91
Ilya Biryukovf01af682017-05-23 13:42:59 +000092 Request();
Ilya Biryukov38d79772017-05-16 09:38:59 +000093 }
94 });
95}
96
97ClangdScheduler::~ClangdScheduler() {
98 if (RunSynchronously)
99 return; // no worker thread is running in that case
100
101 {
102 std::lock_guard<std::mutex> Lock(Mutex);
103 // Wake up the worker thread
104 Done = true;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000105 } // unlock Mutex
Ilya Biryukovf01af682017-05-23 13:42:59 +0000106 RequestCV.notify_one();
Ilya Biryukov38d79772017-05-16 09:38:59 +0000107 Worker.join();
108}
109
Ilya Biryukovf01af682017-05-23 13:42:59 +0000110void ClangdScheduler::addToFront(std::function<void()> Request) {
Ilya Biryukov38d79772017-05-16 09:38:59 +0000111 if (RunSynchronously) {
Ilya Biryukovf01af682017-05-23 13:42:59 +0000112 Request();
Ilya Biryukov38d79772017-05-16 09:38:59 +0000113 return;
114 }
115
Ilya Biryukovf01af682017-05-23 13:42:59 +0000116 {
117 std::lock_guard<std::mutex> Lock(Mutex);
118 RequestQueue.push_front(Request);
119 }
120 RequestCV.notify_one();
121}
122
123void ClangdScheduler::addToEnd(std::function<void()> Request) {
124 if (RunSynchronously) {
125 Request();
126 return;
127 }
128
129 {
130 std::lock_guard<std::mutex> Lock(Mutex);
131 RequestQueue.push_back(Request);
132 }
Ilya Biryukov38d79772017-05-16 09:38:59 +0000133 RequestCV.notify_one();
134}
135
136ClangdServer::ClangdServer(std::unique_ptr<GlobalCompilationDatabase> CDB,
137 std::unique_ptr<DiagnosticsConsumer> DiagConsumer,
138 bool RunSynchronously)
139 : CDB(std::move(CDB)), DiagConsumer(std::move(DiagConsumer)),
140 PCHs(std::make_shared<PCHContainerOperations>()),
Ilya Biryukovf01af682017-05-23 13:42:59 +0000141 WorkScheduler(RunSynchronously) {}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000142
143void ClangdServer::addDocument(PathRef File, StringRef Contents) {
Ilya Biryukovf01af682017-05-23 13:42:59 +0000144 DocVersion Version = DraftMgr.updateDraft(File, Contents);
145 Path FileStr = File;
146 WorkScheduler.addToFront([this, FileStr, Version]() {
147 auto FileContents = DraftMgr.getDraft(FileStr);
148 if (FileContents.Version != Version)
149 return; // This request is outdated, do nothing
150
151 assert(FileContents.Draft &&
152 "No contents inside a file that was scheduled for reparse");
153 Units.runOnUnit(
154 FileStr, *FileContents.Draft, *CDB, PCHs, [&](ClangdUnit const &Unit) {
155 DiagConsumer->onDiagnosticsReady(FileStr, Unit.getLocalDiagnostics());
156 });
157 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000158}
159
160void ClangdServer::removeDocument(PathRef File) {
Ilya Biryukovf01af682017-05-23 13:42:59 +0000161 auto Version = DraftMgr.removeDraft(File);
162 Path FileStr = File;
163 WorkScheduler.addToFront([this, FileStr, Version]() {
164 if (Version != DraftMgr.getVersion(FileStr))
165 return; // This request is outdated, do nothing
166
167 Units.removeUnitIfPresent(FileStr);
168 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000169}
170
171std::vector<CompletionItem> ClangdServer::codeComplete(PathRef File,
172 Position Pos) {
173 auto FileContents = DraftMgr.getDraft(File);
174 assert(FileContents.Draft && "codeComplete is called for non-added document");
175
176 std::vector<CompletionItem> Result;
177 Units.runOnUnitWithoutReparse(
178 File, *FileContents.Draft, *CDB, PCHs, [&](ClangdUnit &Unit) {
179 Result = Unit.codeComplete(*FileContents.Draft, Pos);
180 });
181 return Result;
182}
Ilya Biryukovf01af682017-05-23 13:42:59 +0000183
Ilya Biryukovafb55542017-05-16 14:40:30 +0000184std::vector<tooling::Replacement> ClangdServer::formatRange(PathRef File,
185 Range Rng) {
186 std::string Code = getDocument(File);
187
188 size_t Begin = positionToOffset(Code, Rng.start);
189 size_t Len = positionToOffset(Code, Rng.end) - Begin;
190 return formatCode(Code, File, {tooling::Range(Begin, Len)});
191}
192
193std::vector<tooling::Replacement> ClangdServer::formatFile(PathRef File) {
194 // Format everything.
195 std::string Code = getDocument(File);
196 return formatCode(Code, File, {tooling::Range(0, Code.size())});
197}
198
199std::vector<tooling::Replacement> ClangdServer::formatOnType(PathRef File,
200 Position Pos) {
201 // Look for the previous opening brace from the character position and
202 // format starting from there.
203 std::string Code = getDocument(File);
204 size_t CursorPos = positionToOffset(Code, Pos);
205 size_t PreviousLBracePos = StringRef(Code).find_last_of('{', CursorPos);
206 if (PreviousLBracePos == StringRef::npos)
207 PreviousLBracePos = CursorPos;
208 size_t Len = 1 + CursorPos - PreviousLBracePos;
209
210 return formatCode(Code, File, {tooling::Range(PreviousLBracePos, Len)});
211}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000212
213std::string ClangdServer::getDocument(PathRef File) {
214 auto draft = DraftMgr.getDraft(File);
215 assert(draft.Draft && "File is not tracked, cannot get contents");
216 return *draft.Draft;
217}
218
Ilya Biryukovf01af682017-05-23 13:42:59 +0000219std::string ClangdServer::dumpAST(PathRef File) {
220 std::promise<std::string> DumpPromise;
221 auto DumpFuture = DumpPromise.get_future();
222 auto Version = DraftMgr.getVersion(File);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000223
Ilya Biryukovf01af682017-05-23 13:42:59 +0000224 WorkScheduler.addToEnd([this, &DumpPromise, File, Version]() {
225 assert(DraftMgr.getVersion(File) == Version && "Version has changed");
Ilya Biryukov38d79772017-05-16 09:38:59 +0000226
Ilya Biryukovf01af682017-05-23 13:42:59 +0000227 Units.runOnExistingUnit(File, [&DumpPromise](ClangdUnit &Unit) {
228 std::string Result;
229
230 llvm::raw_string_ostream ResultOS(Result);
231 Unit.dumpAST(ResultOS);
232 ResultOS.flush();
233
234 DumpPromise.set_value(std::move(Result));
235 });
236 });
237 return DumpFuture.get();
Ilya Biryukov38d79772017-05-16 09:38:59 +0000238}