blob: f05984939324053219ac527b82cf83fad7efbd5f [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"
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000016#include "llvm/Support/SourceMgr.h"
Ilya Biryukov687b92a2017-05-16 15:23:55 +000017#include <istream>
18
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000019using namespace clang;
20using namespace clangd;
21
Ilya Biryukov940901e2017-12-13 12:51:22 +000022namespace {
Ilya Biryukov940901e2017-12-13 12:51:22 +000023static Key<json::Expr> RequestID;
24static Key<JSONOutput *> RequestOut;
Sam McCall1b475a12018-01-26 09:00:30 +000025
26// When tracing, we trace a request and attach the repsonse in reply().
27// Because the Span isn't available, we find the current request using Context.
28class RequestSpan {
29 RequestSpan(json::obj *Args) : Args(Args) {}
30 std::mutex Mu;
31 json::obj *Args;
32 static Key<std::unique_ptr<RequestSpan>> Key;
33
34public:
35 // Return a context that's aware of the enclosing request, identified by Span.
36 static Context stash(const trace::Span &Span) {
37 return Span.Ctx.derive(RequestSpan::Key, std::unique_ptr<RequestSpan>(
38 new RequestSpan(Span.Args)));
39 }
40
41 // If there's an enclosing request and the tracer is interested, calls \p F
42 // with a json::obj where request info can be added.
43 template <typename Func> static void attach(const Context &Ctx, Func &&F) {
44 auto *RequestArgs = Ctx.get(RequestSpan::Key);
45 if (!RequestArgs || !*RequestArgs || !(*RequestArgs)->Args)
46 return;
47 std::lock_guard<std::mutex> Lock((*RequestArgs)->Mu);
48 F(*(*RequestArgs)->Args);
49 }
50};
51Key<std::unique_ptr<RequestSpan>> RequestSpan::Key;
Ilya Biryukov940901e2017-12-13 12:51:22 +000052} // namespace
53
Sam McCalldd0566b2017-11-06 15:40:30 +000054void JSONOutput::writeMessage(const json::Expr &Message) {
55 std::string S;
56 llvm::raw_string_ostream OS(S);
57 if (Pretty)
58 OS << llvm::formatv("{0:2}", Message);
59 else
60 OS << Message;
61 OS.flush();
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000062
Benjamin Kramerd0b2ccd2017-02-10 14:08:40 +000063 std::lock_guard<std::mutex> Guard(StreamMutex);
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000064 // Log without headers.
Sam McCalldd0566b2017-11-06 15:40:30 +000065 Logs << "--> " << S << '\n';
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000066 Logs.flush();
67
68 // Emit message with header.
Sam McCalldd0566b2017-11-06 15:40:30 +000069 Outs << "Content-Length: " << S.size() << "\r\n\r\n" << S;
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000070 Outs.flush();
71}
72
Ilya Biryukov940901e2017-12-13 12:51:22 +000073void JSONOutput::log(const Context &Ctx, const Twine &Message) {
Ilya Biryukovee27d2e2017-12-14 15:04:59 +000074 trace::log(Ctx, Message);
Benjamin Kramere14bd422017-02-15 16:44:11 +000075 std::lock_guard<std::mutex> Guard(StreamMutex);
Sam McCall318fbeb2017-11-30 23:21:34 +000076 Logs << Message << '\n';
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
Ilya Biryukov940901e2017-12-13 12:51:22 +000088void clangd::reply(const Context &Ctx, json::Expr &&Result) {
89 auto ID = Ctx.get(RequestID);
Sam McCalldd0566b2017-11-06 15:40:30 +000090 if (!ID) {
Ilya Biryukov940901e2017-12-13 12:51:22 +000091 log(Ctx, "Attempted to reply to a notification!");
Sam McCall8a5dded2017-10-12 13:29:58 +000092 return;
93 }
Ilya Biryukov940901e2017-12-13 12:51:22 +000094
Sam McCall1b475a12018-01-26 09:00:30 +000095 RequestSpan::attach(Ctx, [&](json::obj &Args) { Args["Reply"] = Result; });
Ilya Biryukov940901e2017-12-13 12:51:22 +000096
97 Ctx.getExisting(RequestOut)
98 ->writeMessage(json::obj{
99 {"jsonrpc", "2.0"},
100 {"id", *ID},
101 {"result", std::move(Result)},
102 });
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000103}
104
Ilya Biryukov940901e2017-12-13 12:51:22 +0000105void clangd::replyError(const Context &Ctx, ErrorCode code,
106 const llvm::StringRef &Message) {
107 log(Ctx, "Error " + Twine(static_cast<int>(code)) + ": " + Message);
Sam McCall1b475a12018-01-26 09:00:30 +0000108 RequestSpan::attach(Ctx, [&](json::obj &Args) {
109 Args["Error"] =
110 json::obj{{"code", static_cast<int>(code)}, {"message", Message.str()}};
111 });
Ilya Biryukov940901e2017-12-13 12:51:22 +0000112
113 if (auto ID = Ctx.get(RequestID)) {
114 Ctx.getExisting(RequestOut)
115 ->writeMessage(json::obj{
116 {"jsonrpc", "2.0"},
117 {"id", *ID},
118 {"error",
119 json::obj{{"code", static_cast<int>(code)}, {"message", Message}}},
120 });
Sam McCall8a5dded2017-10-12 13:29:58 +0000121 }
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000122}
123
Ilya Biryukov940901e2017-12-13 12:51:22 +0000124void clangd::call(const Context &Ctx, StringRef Method, json::Expr &&Params) {
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000125 // FIXME: Generate/Increment IDs for every request so that we can get proper
126 // replies once we need to.
Sam McCall1b475a12018-01-26 09:00:30 +0000127 RequestSpan::attach(Ctx, [&](json::obj &Args) {
128 Args["Call"] = json::obj{{"method", Method.str()}, {"params", Params}};
129 });
Ilya Biryukov940901e2017-12-13 12:51:22 +0000130 Ctx.getExisting(RequestOut)
131 ->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.
166 auto Ctx = Context::empty().derive(RequestOut, &Out);
167 if (ID)
168 Ctx = std::move(Ctx).derive(RequestID, *ID);
169
170 // Create a tracing Span covering the whole request lifetime.
Sam McCall1b475a12018-01-26 09:00:30 +0000171 trace::Span Tracer(Ctx, *Method);
Ilya Biryukov940901e2017-12-13 12:51:22 +0000172 if (ID)
Sam McCall1b475a12018-01-26 09:00:30 +0000173 SPAN_ATTACH(Tracer, "ID", *ID);
174 SPAN_ATTACH(Tracer, "Params", Params);
Ilya Biryukov940901e2017-12-13 12:51:22 +0000175
Sam McCall1b475a12018-01-26 09:00:30 +0000176 // Stash a reference to the span args, so later calls can add metadata.
177 Handler(RequestSpan::stash(Tracer), std::move(Params));
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000178 return true;
179}
Ilya Biryukovafb55542017-05-16 14:40:30 +0000180
181void clangd::runLanguageServerLoop(std::istream &In, JSONOutput &Out,
182 JSONRPCDispatcher &Dispatcher,
183 bool &IsDone) {
184 while (In.good()) {
Ilya Biryukov1fab4f82017-09-04 12:28:15 +0000185 // 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;
188 while (In.good()) {
189 std::string Line;
190 std::getline(In, Line);
191 if (!In.good() && errno == EINTR) {
192 In.clear();
193 continue;
194 }
195
Ilya Biryukove6dbb582017-10-10 09:08:47 +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");
203
Ilya Biryukov1fab4f82017-09-04 12:28:15 +0000204 llvm::StringRef LineRef(Line);
205
Sam McCallec109022017-11-28 09:37:43 +0000206 // We allow comments in headers. Technically this isn't part
Ilya Biryukov1fab4f82017-09-04 12:28:15 +0000207 // 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) {
Ilya Biryukov940901e2017-12-13 12:51:22 +0000219 log(Context::empty(),
220 "Warning: Duplicate Content-Length header received. "
221 "The previous value for this message (" +
Benjamin Kramer3a13ed62017-12-28 16:58:54 +0000222 llvm::Twine(ContentLength) + ") was ignored.\n");
Ilya Biryukov1fab4f82017-09-04 12:28:15 +0000223 }
224
225 llvm::getAsUnsignedInteger(LineRef.trim(), 0, ContentLength);
226 continue;
227 } else if (!LineRef.trim().empty()) {
228 // It's another header, ignore it.
229 continue;
230 } else {
231 // An empty line indicates the end of headers.
232 // Go ahead and read the JSON.
233 break;
234 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000235 }
236
Benjamin Kramer1d053792017-10-27 17:06:41 +0000237 // Guard against large messages. This is usually a bug in the client code
238 // and we don't want to crash downstream because of it.
239 if (ContentLength > 1 << 30) { // 1024M
240 In.ignore(ContentLength);
Ilya Biryukov940901e2017-12-13 12:51:22 +0000241 log(Context::empty(), "Skipped overly large message of " +
242 Twine(ContentLength) + " bytes.\n");
Benjamin Kramer1d053792017-10-27 17:06:41 +0000243 continue;
244 }
245
Ilya Biryukov1fab4f82017-09-04 12:28:15 +0000246 if (ContentLength > 0) {
Sam McCallec109022017-11-28 09:37:43 +0000247 std::vector<char> JSON(ContentLength);
Sam McCall8567cb32017-11-02 09:21:51 +0000248 llvm::StringRef JSONRef;
249 {
Sam McCall8567cb32017-11-02 09:21:51 +0000250 In.read(JSON.data(), ContentLength);
251 Out.mirrorInput(StringRef(JSON.data(), In.gcount()));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000252
Sam McCall8567cb32017-11-02 09:21:51 +0000253 // If the stream is aborted before we read ContentLength bytes, In
254 // will have eofbit and failbit set.
255 if (!In) {
Benjamin Kramer3a13ed62017-12-28 16:58:54 +0000256 log(Context::empty(),
257 "Input was aborted. Read only " + llvm::Twine(In.gcount()) +
258 " bytes of expected " + llvm::Twine(ContentLength) + ".\n");
Sam McCall8567cb32017-11-02 09:21:51 +0000259 break;
260 }
261
262 JSONRef = StringRef(JSON.data(), ContentLength);
Ilya Biryukov1fab4f82017-09-04 12:28:15 +0000263 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000264
Sam McCallec109022017-11-28 09:37:43 +0000265 if (auto Doc = json::parse(JSONRef)) {
266 // Log the formatted message.
Ilya Biryukov940901e2017-12-13 12:51:22 +0000267 log(Context::empty(),
268 llvm::formatv(Out.Pretty ? "<-- {0:2}\n" : "<-- {0}\n", *Doc));
Sam McCallec109022017-11-28 09:37:43 +0000269 // Finally, execute the action for this JSON message.
270 if (!Dispatcher.call(*Doc, Out))
Ilya Biryukov940901e2017-12-13 12:51:22 +0000271 log(Context::empty(), "JSON dispatch failed!\n");
Sam McCallec109022017-11-28 09:37:43 +0000272 } else {
273 // Parse error. Log the raw message.
Ilya Biryukov940901e2017-12-13 12:51:22 +0000274 log(Context::empty(), "<-- " + JSONRef + "\n");
275 log(Context::empty(), llvm::Twine("JSON parse error: ") +
276 llvm::toString(Doc.takeError()) + "\n");
Sam McCallec109022017-11-28 09:37:43 +0000277 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000278
279 // If we're done, exit the loop.
280 if (IsDone)
281 break;
Ilya Biryukov1fab4f82017-09-04 12:28:15 +0000282 } else {
Ilya Biryukov940901e2017-12-13 12:51:22 +0000283 log(Context::empty(),
284 "Warning: Missing Content-Length header, or message has zero "
285 "length.\n");
Ilya Biryukovafb55542017-05-16 14:40:30 +0000286 }
287 }
288}