blob: 2cf4da31c4cbac1b6cb74f84443ac8f75368a65c [file] [log] [blame]
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +00001//===--- JSONRPCDispatcher.cpp - Main JSON parser entry point -------------===//
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 "JSONRPCDispatcher.h"
Sam McCalldd0566b2017-11-06 15:40:30 +000011#include "JSONExpr.h"
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000012#include "ProtocolHandlers.h"
Sam McCall8567cb32017-11-02 09:21:51 +000013#include "Trace.h"
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000014#include "llvm/ADT/SmallString.h"
Sam McCall94362c62017-11-07 14:45:31 +000015#include "llvm/ADT/StringExtras.h"
Sam McCalla90f2572018-02-16 16:41:42 +000016#include "llvm/Support/Chrono.h"
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000017#include "llvm/Support/SourceMgr.h"
Ilya Biryukov687b92a2017-05-16 15:23:55 +000018#include <istream>
19
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000020using namespace clang;
21using namespace clangd;
22
Ilya Biryukov940901e2017-12-13 12:51:22 +000023namespace {
Ilya Biryukov940901e2017-12-13 12:51:22 +000024static Key<json::Expr> RequestID;
25static Key<JSONOutput *> RequestOut;
Sam McCall1b475a12018-01-26 09:00:30 +000026
27// When tracing, we trace a request and attach the repsonse in reply().
28// Because the Span isn't available, we find the current request using Context.
29class RequestSpan {
30 RequestSpan(json::obj *Args) : Args(Args) {}
31 std::mutex Mu;
32 json::obj *Args;
Sam McCall24f0fa32018-01-26 11:23:33 +000033 static Key<std::unique_ptr<RequestSpan>> RSKey;
Sam McCall1b475a12018-01-26 09:00:30 +000034
35public:
36 // Return a context that's aware of the enclosing request, identified by Span.
37 static Context stash(const trace::Span &Span) {
Sam McCalld1a7a372018-01-31 13:40:48 +000038 return Context::current().derive(
39 RSKey, std::unique_ptr<RequestSpan>(new RequestSpan(Span.Args)));
Sam McCall1b475a12018-01-26 09:00:30 +000040 }
41
42 // If there's an enclosing request and the tracer is interested, calls \p F
43 // with a json::obj where request info can be added.
Sam McCalld1a7a372018-01-31 13:40:48 +000044 template <typename Func> static void attach(Func &&F) {
45 auto *RequestArgs = Context::current().get(RSKey);
Sam McCall1b475a12018-01-26 09:00:30 +000046 if (!RequestArgs || !*RequestArgs || !(*RequestArgs)->Args)
47 return;
48 std::lock_guard<std::mutex> Lock((*RequestArgs)->Mu);
49 F(*(*RequestArgs)->Args);
50 }
51};
Sam McCall24f0fa32018-01-26 11:23:33 +000052Key<std::unique_ptr<RequestSpan>> RequestSpan::RSKey;
Ilya Biryukov940901e2017-12-13 12:51:22 +000053} // namespace
54
Sam McCalldd0566b2017-11-06 15:40:30 +000055void JSONOutput::writeMessage(const json::Expr &Message) {
56 std::string S;
57 llvm::raw_string_ostream OS(S);
58 if (Pretty)
59 OS << llvm::formatv("{0:2}", Message);
60 else
61 OS << Message;
62 OS.flush();
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000063
Sam McCalla90f2572018-02-16 16:41:42 +000064 {
65 std::lock_guard<std::mutex> Guard(StreamMutex);
66 Outs << "Content-Length: " << S.size() << "\r\n\r\n" << S;
67 Outs.flush();
68 }
69 log(llvm::Twine("--> ") + S);
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000070}
71
Sam McCalld1a7a372018-01-31 13:40:48 +000072void JSONOutput::log(const Twine &Message) {
Sam McCalla90f2572018-02-16 16:41:42 +000073 llvm::sys::TimePoint<> Timestamp = std::chrono::system_clock::now();
Sam McCalld1a7a372018-01-31 13:40:48 +000074 trace::log(Message);
Benjamin Kramere14bd422017-02-15 16:44:11 +000075 std::lock_guard<std::mutex> Guard(StreamMutex);
Sam McCalla90f2572018-02-16 16:41:42 +000076 Logs << llvm::formatv("[{0:%H:%M:%S.%L}] {1}\n", Timestamp, Message);
Benjamin Kramere14bd422017-02-15 16:44:11 +000077 Logs.flush();
78}
79
Ilya Biryukove6dbb582017-10-10 09:08:47 +000080void JSONOutput::mirrorInput(const Twine &Message) {
81 if (!InputMirror)
82 return;
83
84 *InputMirror << Message;
85 InputMirror->flush();
86}
87
Sam McCalld1a7a372018-01-31 13:40:48 +000088void clangd::reply(json::Expr &&Result) {
89 auto ID = Context::current().get(RequestID);
Sam McCalldd0566b2017-11-06 15:40:30 +000090 if (!ID) {
Sam McCalld1a7a372018-01-31 13:40:48 +000091 log("Attempted to reply to a notification!");
Sam McCall8a5dded2017-10-12 13:29:58 +000092 return;
93 }
Sam McCalld1a7a372018-01-31 13:40:48 +000094 RequestSpan::attach([&](json::obj &Args) { Args["Reply"] = Result; });
95 Context::current()
96 .getExisting(RequestOut)
Ilya Biryukov940901e2017-12-13 12:51:22 +000097 ->writeMessage(json::obj{
98 {"jsonrpc", "2.0"},
99 {"id", *ID},
100 {"result", std::move(Result)},
101 });
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000102}
103
Sam McCalld1a7a372018-01-31 13:40:48 +0000104void clangd::replyError(ErrorCode code, const llvm::StringRef &Message) {
105 log("Error " + Twine(static_cast<int>(code)) + ": " + Message);
106 RequestSpan::attach([&](json::obj &Args) {
Sam McCall1b475a12018-01-26 09:00:30 +0000107 Args["Error"] =
108 json::obj{{"code", static_cast<int>(code)}, {"message", Message.str()}};
109 });
Ilya Biryukov940901e2017-12-13 12:51:22 +0000110
Sam McCalld1a7a372018-01-31 13:40:48 +0000111 if (auto ID = Context::current().get(RequestID)) {
112 Context::current()
113 .getExisting(RequestOut)
Ilya Biryukov940901e2017-12-13 12:51:22 +0000114 ->writeMessage(json::obj{
115 {"jsonrpc", "2.0"},
116 {"id", *ID},
117 {"error",
118 json::obj{{"code", static_cast<int>(code)}, {"message", Message}}},
119 });
Sam McCall8a5dded2017-10-12 13:29:58 +0000120 }
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000121}
122
Sam McCalld1a7a372018-01-31 13:40:48 +0000123void clangd::call(StringRef Method, json::Expr &&Params) {
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000124 // FIXME: Generate/Increment IDs for every request so that we can get proper
125 // replies once we need to.
Sam McCalld1a7a372018-01-31 13:40:48 +0000126 RequestSpan::attach([&](json::obj &Args) {
Sam McCall1b475a12018-01-26 09:00:30 +0000127 Args["Call"] = json::obj{{"method", Method.str()}, {"params", Params}};
128 });
Sam McCalld1a7a372018-01-31 13:40:48 +0000129 Context::current()
130 .getExisting(RequestOut)
Ilya Biryukov940901e2017-12-13 12:51:22 +0000131 ->writeMessage(json::obj{
132 {"jsonrpc", "2.0"},
133 {"id", 1},
134 {"method", Method},
135 {"params", std::move(Params)},
136 });
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000137}
138
Sam McCall8a5dded2017-10-12 13:29:58 +0000139void JSONRPCDispatcher::registerHandler(StringRef Method, Handler H) {
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000140 assert(!Handlers.count(Method) && "Handler already registered!");
141 Handlers[Method] = std::move(H);
142}
143
Sam McCallec109022017-11-28 09:37:43 +0000144bool JSONRPCDispatcher::call(const json::Expr &Message, JSONOutput &Out) const {
145 // Message must be an object with "jsonrpc":"2.0".
146 auto *Object = Message.asObject();
147 if (!Object || Object->getString("jsonrpc") != Optional<StringRef>("2.0"))
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000148 return false;
Sam McCallec109022017-11-28 09:37:43 +0000149 // ID may be any JSON value. If absent, this is a notification.
Sam McCalldd0566b2017-11-06 15:40:30 +0000150 llvm::Optional<json::Expr> ID;
Sam McCallec109022017-11-28 09:37:43 +0000151 if (auto *I = Object->get("id"))
152 ID = std::move(*I);
153 // Method must be given.
154 auto Method = Object->getString("method");
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000155 if (!Method)
156 return false;
Sam McCallec109022017-11-28 09:37:43 +0000157 // Params should be given, use null if not.
158 json::Expr Params = nullptr;
159 if (auto *P = Object->get("params"))
160 Params = std::move(*P);
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000161
Sam McCallec109022017-11-28 09:37:43 +0000162 auto I = Handlers.find(*Method);
163 auto &Handler = I != Handlers.end() ? I->second : UnknownHandler;
Ilya Biryukov940901e2017-12-13 12:51:22 +0000164
Ilya Biryukovee27d2e2017-12-14 15:04:59 +0000165 // Create a Context that contains request information.
Sam McCalld1a7a372018-01-31 13:40:48 +0000166 WithContextValue WithRequestOut(RequestOut, &Out);
167 llvm::Optional<WithContextValue> WithID;
Ilya Biryukovee27d2e2017-12-14 15:04:59 +0000168 if (ID)
Sam McCalld1a7a372018-01-31 13:40:48 +0000169 WithID.emplace(RequestID, *ID);
Ilya Biryukovee27d2e2017-12-14 15:04:59 +0000170
171 // Create a tracing Span covering the whole request lifetime.
Sam McCalld1a7a372018-01-31 13:40:48 +0000172 trace::Span Tracer(*Method);
Ilya Biryukov940901e2017-12-13 12:51:22 +0000173 if (ID)
Sam McCall1b475a12018-01-26 09:00:30 +0000174 SPAN_ATTACH(Tracer, "ID", *ID);
175 SPAN_ATTACH(Tracer, "Params", Params);
Ilya Biryukov940901e2017-12-13 12:51:22 +0000176
Sam McCall1b475a12018-01-26 09:00:30 +0000177 // Stash a reference to the span args, so later calls can add metadata.
Sam McCalld1a7a372018-01-31 13:40:48 +0000178 WithContext WithRequestSpan(RequestSpan::stash(Tracer));
179 Handler(std::move(Params));
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000180 return true;
181}
Ilya Biryukovafb55542017-05-16 14:40:30 +0000182
Sam McCall5ed599e2018-02-06 10:47:30 +0000183static llvm::Optional<std::string> readStandardMessage(std::istream &In,
184 JSONOutput &Out) {
185 // A Language Server Protocol message starts with a set of HTTP headers,
186 // delimited by \r\n, and terminated by an empty line (\r\n).
187 unsigned long long ContentLength = 0;
Ilya Biryukovafb55542017-05-16 14:40:30 +0000188 while (In.good()) {
Sam McCall5ed599e2018-02-06 10:47:30 +0000189 std::string Line;
190 std::getline(In, Line);
191 if (!In.good() && errno == EINTR) {
192 In.clear();
Benjamin Kramer1d053792017-10-27 17:06:41 +0000193 continue;
194 }
195
Sam McCall5ed599e2018-02-06 10:47:30 +0000196 Out.mirrorInput(Line);
197 // Mirror '\n' that gets consumed by std::getline, but is not included in
198 // the resulting Line.
199 // Note that '\r' is part of Line, so we don't need to mirror it
200 // separately.
201 if (!In.eof())
202 Out.mirrorInput("\n");
Ilya Biryukovafb55542017-05-16 14:40:30 +0000203
Sam McCall5ed599e2018-02-06 10:47:30 +0000204 llvm::StringRef LineRef(Line);
Sam McCall8567cb32017-11-02 09:21:51 +0000205
Sam McCall5ed599e2018-02-06 10:47:30 +0000206 // We allow comments in headers. Technically this isn't part
207 // of the LSP specification, but makes writing tests easier.
208 if (LineRef.startswith("#"))
209 continue;
210
211 // Content-Type is a specified header, but does nothing.
212 // Content-Length is a mandatory header. It specifies the length of the
213 // following JSON.
214 // It is unspecified what sequence headers must be supplied in, so we
215 // allow any sequence.
216 // The end of headers is signified by an empty line.
217 if (LineRef.consume_front("Content-Length: ")) {
218 if (ContentLength != 0) {
219 log("Warning: Duplicate Content-Length header received. "
220 "The previous value for this message (" +
221 llvm::Twine(ContentLength) + ") was ignored.\n");
Ilya Biryukov1fab4f82017-09-04 12:28:15 +0000222 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000223
Sam McCall5ed599e2018-02-06 10:47:30 +0000224 llvm::getAsUnsignedInteger(LineRef.trim(), 0, ContentLength);
225 continue;
226 } else if (!LineRef.trim().empty()) {
227 // It's another header, ignore it.
228 continue;
229 } else {
230 // An empty line indicates the end of headers.
231 // Go ahead and read the JSON.
232 break;
233 }
234 }
235
236 // Guard against large messages. This is usually a bug in the client code
237 // and we don't want to crash downstream because of it.
238 if (ContentLength > 1 << 30) { // 1024M
239 In.ignore(ContentLength);
240 log("Skipped overly large message of " + Twine(ContentLength) +
241 " bytes.\n");
242 return llvm::None;
243 }
244
245 if (ContentLength > 0) {
246 std::string JSON(ContentLength, '\0');
Sam McCall5ed599e2018-02-06 10:47:30 +0000247 In.read(&JSON[0], ContentLength);
248 Out.mirrorInput(StringRef(JSON.data(), In.gcount()));
249
250 // If the stream is aborted before we read ContentLength bytes, In
251 // will have eofbit and failbit set.
252 if (!In) {
253 log("Input was aborted. Read only " + llvm::Twine(In.gcount()) +
254 " bytes of expected " + llvm::Twine(ContentLength) + ".\n");
255 return llvm::None;
256 }
257 return std::move(JSON);
258 } else {
259 log("Warning: Missing Content-Length header, or message has zero "
260 "length.\n");
261 return llvm::None;
262 }
263}
264
265// For lit tests we support a simplified syntax:
266// - messages are delimited by '---' on a line by itself
267// - lines starting with # are ignored.
268// This is a testing path, so favor simplicity over performance here.
269static llvm::Optional<std::string> readDelimitedMessage(std::istream &In,
270 JSONOutput &Out) {
271 std::string JSON;
272 std::string Line;
273 while (std::getline(In, Line)) {
Jan Korous6269d342018-04-12 21:33:24 +0000274 Line.push_back('\n'); // getline() consumed the newline.
275
Sam McCall5ed599e2018-02-06 10:47:30 +0000276 auto LineRef = llvm::StringRef(Line).trim();
277 if (LineRef.startswith("#")) // comment
278 continue;
279
280 bool IsDelim = LineRef.find_first_not_of('-') == llvm::StringRef::npos;
281 if (!IsDelim) // Line is part of a JSON message.
282 JSON += Line;
Jan Korous6269d342018-04-12 21:33:24 +0000283 if (IsDelim) {
Sam McCall5ed599e2018-02-06 10:47:30 +0000284 Out.mirrorInput(
285 llvm::formatv("Content-Length: {0}\r\n\r\n{1}", JSON.size(), JSON));
286 return std::move(JSON);
287 }
288 }
289
290 if (In.bad()) {
291 log("Input error while reading message!");
292 return llvm::None;
293 } else {
294 log("Input message terminated by EOF");
295 return std::move(JSON);
296 }
297}
298
299void clangd::runLanguageServerLoop(std::istream &In, JSONOutput &Out,
300 JSONStreamStyle InputStyle,
301 JSONRPCDispatcher &Dispatcher,
302 bool &IsDone) {
303 auto &ReadMessage =
304 (InputStyle == Delimited) ? readDelimitedMessage : readStandardMessage;
305 while (In.good()) {
306 if (auto JSON = ReadMessage(In, Out)) {
307 if (auto Doc = json::parse(*JSON)) {
Sam McCallec109022017-11-28 09:37:43 +0000308 // Log the formatted message.
Sam McCalld1a7a372018-01-31 13:40:48 +0000309 log(llvm::formatv(Out.Pretty ? "<-- {0:2}\n" : "<-- {0}\n", *Doc));
Sam McCallec109022017-11-28 09:37:43 +0000310 // Finally, execute the action for this JSON message.
311 if (!Dispatcher.call(*Doc, Out))
Sam McCalld1a7a372018-01-31 13:40:48 +0000312 log("JSON dispatch failed!\n");
Sam McCallec109022017-11-28 09:37:43 +0000313 } else {
314 // Parse error. Log the raw message.
Sam McCall5ed599e2018-02-06 10:47:30 +0000315 log(llvm::formatv("<-- {0}\n" , *JSON));
Sam McCalld1a7a372018-01-31 13:40:48 +0000316 log(llvm::Twine("JSON parse error: ") +
317 llvm::toString(Doc.takeError()) + "\n");
Sam McCallec109022017-11-28 09:37:43 +0000318 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000319 }
Sam McCall5ed599e2018-02-06 10:47:30 +0000320 // If we're done, exit the loop.
321 if (IsDone)
322 break;
Ilya Biryukovafb55542017-05-16 14:40:30 +0000323 }
324}