blob: c67221a23f49396e9ab278a46ba919a062c0d5d3 [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 {
23static Key<std::unique_ptr<trace::Span>> RequestSpan;
24static Key<json::Expr> RequestID;
25static Key<JSONOutput *> RequestOut;
26} // namespace
27
Sam McCalldd0566b2017-11-06 15:40:30 +000028void JSONOutput::writeMessage(const json::Expr &Message) {
29 std::string S;
30 llvm::raw_string_ostream OS(S);
31 if (Pretty)
32 OS << llvm::formatv("{0:2}", Message);
33 else
34 OS << Message;
35 OS.flush();
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000036
Benjamin Kramerd0b2ccd2017-02-10 14:08:40 +000037 std::lock_guard<std::mutex> Guard(StreamMutex);
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000038 // Log without headers.
Sam McCalldd0566b2017-11-06 15:40:30 +000039 Logs << "--> " << S << '\n';
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000040 Logs.flush();
41
42 // Emit message with header.
Sam McCalldd0566b2017-11-06 15:40:30 +000043 Outs << "Content-Length: " << S.size() << "\r\n\r\n" << S;
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000044 Outs.flush();
45}
46
Ilya Biryukov940901e2017-12-13 12:51:22 +000047void JSONOutput::log(const Context &Ctx, const Twine &Message) {
Ilya Biryukovee27d2e2017-12-14 15:04:59 +000048 trace::log(Ctx, Message);
Benjamin Kramere14bd422017-02-15 16:44:11 +000049 std::lock_guard<std::mutex> Guard(StreamMutex);
Sam McCall318fbeb2017-11-30 23:21:34 +000050 Logs << Message << '\n';
Benjamin Kramere14bd422017-02-15 16:44:11 +000051 Logs.flush();
52}
53
Ilya Biryukove6dbb582017-10-10 09:08:47 +000054void JSONOutput::mirrorInput(const Twine &Message) {
55 if (!InputMirror)
56 return;
57
58 *InputMirror << Message;
59 InputMirror->flush();
60}
61
Ilya Biryukov940901e2017-12-13 12:51:22 +000062void clangd::reply(const Context &Ctx, json::Expr &&Result) {
63 auto ID = Ctx.get(RequestID);
Sam McCalldd0566b2017-11-06 15:40:30 +000064 if (!ID) {
Ilya Biryukov940901e2017-12-13 12:51:22 +000065 log(Ctx, "Attempted to reply to a notification!");
Sam McCall8a5dded2017-10-12 13:29:58 +000066 return;
67 }
Ilya Biryukov940901e2017-12-13 12:51:22 +000068
69 if (auto *Span = Ctx.get(RequestSpan))
70 SPAN_ATTACH(**Span, "Reply", Result);
71
72 Ctx.getExisting(RequestOut)
73 ->writeMessage(json::obj{
74 {"jsonrpc", "2.0"},
75 {"id", *ID},
76 {"result", std::move(Result)},
77 });
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000078}
79
Ilya Biryukov940901e2017-12-13 12:51:22 +000080void clangd::replyError(const Context &Ctx, ErrorCode code,
81 const llvm::StringRef &Message) {
82 log(Ctx, "Error " + Twine(static_cast<int>(code)) + ": " + Message);
83 if (auto *Span = Ctx.get(RequestSpan))
84 SPAN_ATTACH(**Span, "Error",
85 (json::obj{{"code", static_cast<int>(code)},
86 {"message", Message.str()}}));
87
88 if (auto ID = Ctx.get(RequestID)) {
89 Ctx.getExisting(RequestOut)
90 ->writeMessage(json::obj{
91 {"jsonrpc", "2.0"},
92 {"id", *ID},
93 {"error",
94 json::obj{{"code", static_cast<int>(code)}, {"message", Message}}},
95 });
Sam McCall8a5dded2017-10-12 13:29:58 +000096 }
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000097}
98
Ilya Biryukov940901e2017-12-13 12:51:22 +000099void clangd::call(const Context &Ctx, StringRef Method, json::Expr &&Params) {
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000100 // FIXME: Generate/Increment IDs for every request so that we can get proper
101 // replies once we need to.
Ilya Biryukov940901e2017-12-13 12:51:22 +0000102 if (auto *Span = Ctx.get(RequestSpan))
103 SPAN_ATTACH(**Span, "Call",
104 (json::obj{{"method", Method.str()}, {"params", Params}}));
105 Ctx.getExisting(RequestOut)
106 ->writeMessage(json::obj{
107 {"jsonrpc", "2.0"},
108 {"id", 1},
109 {"method", Method},
110 {"params", std::move(Params)},
111 });
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000112}
113
Sam McCall8a5dded2017-10-12 13:29:58 +0000114void JSONRPCDispatcher::registerHandler(StringRef Method, Handler H) {
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000115 assert(!Handlers.count(Method) && "Handler already registered!");
116 Handlers[Method] = std::move(H);
117}
118
Sam McCallec109022017-11-28 09:37:43 +0000119bool JSONRPCDispatcher::call(const json::Expr &Message, JSONOutput &Out) const {
120 // Message must be an object with "jsonrpc":"2.0".
121 auto *Object = Message.asObject();
122 if (!Object || Object->getString("jsonrpc") != Optional<StringRef>("2.0"))
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000123 return false;
Sam McCallec109022017-11-28 09:37:43 +0000124 // ID may be any JSON value. If absent, this is a notification.
Sam McCalldd0566b2017-11-06 15:40:30 +0000125 llvm::Optional<json::Expr> ID;
Sam McCallec109022017-11-28 09:37:43 +0000126 if (auto *I = Object->get("id"))
127 ID = std::move(*I);
128 // Method must be given.
129 auto Method = Object->getString("method");
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000130 if (!Method)
131 return false;
Sam McCallec109022017-11-28 09:37:43 +0000132 // Params should be given, use null if not.
133 json::Expr Params = nullptr;
134 if (auto *P = Object->get("params"))
135 Params = std::move(*P);
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000136
Sam McCallec109022017-11-28 09:37:43 +0000137 auto I = Handlers.find(*Method);
138 auto &Handler = I != Handlers.end() ? I->second : UnknownHandler;
Ilya Biryukov940901e2017-12-13 12:51:22 +0000139
Ilya Biryukovee27d2e2017-12-14 15:04:59 +0000140 // Create a Context that contains request information.
141 auto Ctx = Context::empty().derive(RequestOut, &Out);
142 if (ID)
143 Ctx = std::move(Ctx).derive(RequestID, *ID);
144
145 // Create a tracing Span covering the whole request lifetime.
146 auto Tracer = llvm::make_unique<trace::Span>(Ctx, *Method);
Ilya Biryukov940901e2017-12-13 12:51:22 +0000147 if (ID)
148 SPAN_ATTACH(*Tracer, "ID", *ID);
149 SPAN_ATTACH(*Tracer, "Params", Params);
150
Ilya Biryukovee27d2e2017-12-14 15:04:59 +0000151 // Update Ctx to include Tracer.
152 Ctx = std::move(Ctx).derive(RequestSpan, std::move(Tracer));
Ilya Biryukov940901e2017-12-13 12:51:22 +0000153
Sam McCallec109022017-11-28 09:37:43 +0000154 Handler(std::move(Ctx), std::move(Params));
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000155 return true;
156}
Ilya Biryukovafb55542017-05-16 14:40:30 +0000157
158void clangd::runLanguageServerLoop(std::istream &In, JSONOutput &Out,
159 JSONRPCDispatcher &Dispatcher,
160 bool &IsDone) {
161 while (In.good()) {
Ilya Biryukov1fab4f82017-09-04 12:28:15 +0000162 // A Language Server Protocol message starts with a set of HTTP headers,
163 // delimited by \r\n, and terminated by an empty line (\r\n).
164 unsigned long long ContentLength = 0;
165 while (In.good()) {
166 std::string Line;
167 std::getline(In, Line);
168 if (!In.good() && errno == EINTR) {
169 In.clear();
170 continue;
171 }
172
Ilya Biryukove6dbb582017-10-10 09:08:47 +0000173 Out.mirrorInput(Line);
174 // Mirror '\n' that gets consumed by std::getline, but is not included in
175 // the resulting Line.
176 // Note that '\r' is part of Line, so we don't need to mirror it
177 // separately.
178 if (!In.eof())
179 Out.mirrorInput("\n");
180
Ilya Biryukov1fab4f82017-09-04 12:28:15 +0000181 llvm::StringRef LineRef(Line);
182
Sam McCallec109022017-11-28 09:37:43 +0000183 // We allow comments in headers. Technically this isn't part
Ilya Biryukov1fab4f82017-09-04 12:28:15 +0000184 // of the LSP specification, but makes writing tests easier.
185 if (LineRef.startswith("#"))
186 continue;
187
188 // Content-Type is a specified header, but does nothing.
189 // Content-Length is a mandatory header. It specifies the length of the
190 // following JSON.
191 // It is unspecified what sequence headers must be supplied in, so we
192 // allow any sequence.
193 // The end of headers is signified by an empty line.
194 if (LineRef.consume_front("Content-Length: ")) {
195 if (ContentLength != 0) {
Ilya Biryukov940901e2017-12-13 12:51:22 +0000196 log(Context::empty(),
197 "Warning: Duplicate Content-Length header received. "
198 "The previous value for this message (" +
199 std::to_string(ContentLength) + ") was ignored.\n");
Ilya Biryukov1fab4f82017-09-04 12:28:15 +0000200 }
201
202 llvm::getAsUnsignedInteger(LineRef.trim(), 0, ContentLength);
203 continue;
204 } else if (!LineRef.trim().empty()) {
205 // It's another header, ignore it.
206 continue;
207 } else {
208 // An empty line indicates the end of headers.
209 // Go ahead and read the JSON.
210 break;
211 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000212 }
213
Benjamin Kramer1d053792017-10-27 17:06:41 +0000214 // Guard against large messages. This is usually a bug in the client code
215 // and we don't want to crash downstream because of it.
216 if (ContentLength > 1 << 30) { // 1024M
217 In.ignore(ContentLength);
Ilya Biryukov940901e2017-12-13 12:51:22 +0000218 log(Context::empty(), "Skipped overly large message of " +
219 Twine(ContentLength) + " bytes.\n");
Benjamin Kramer1d053792017-10-27 17:06:41 +0000220 continue;
221 }
222
Ilya Biryukov1fab4f82017-09-04 12:28:15 +0000223 if (ContentLength > 0) {
Sam McCallec109022017-11-28 09:37:43 +0000224 std::vector<char> JSON(ContentLength);
Sam McCall8567cb32017-11-02 09:21:51 +0000225 llvm::StringRef JSONRef;
226 {
Sam McCall8567cb32017-11-02 09:21:51 +0000227 In.read(JSON.data(), ContentLength);
228 Out.mirrorInput(StringRef(JSON.data(), In.gcount()));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000229
Sam McCall8567cb32017-11-02 09:21:51 +0000230 // If the stream is aborted before we read ContentLength bytes, In
231 // will have eofbit and failbit set.
232 if (!In) {
Ilya Biryukov940901e2017-12-13 12:51:22 +0000233 log(Context::empty(), "Input was aborted. Read only " +
234 std::to_string(In.gcount()) +
235 " bytes of expected " +
236 std::to_string(ContentLength) + ".\n");
Sam McCall8567cb32017-11-02 09:21:51 +0000237 break;
238 }
239
240 JSONRef = StringRef(JSON.data(), ContentLength);
Ilya Biryukov1fab4f82017-09-04 12:28:15 +0000241 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000242
Sam McCallec109022017-11-28 09:37:43 +0000243 if (auto Doc = json::parse(JSONRef)) {
244 // Log the formatted message.
Ilya Biryukov940901e2017-12-13 12:51:22 +0000245 log(Context::empty(),
246 llvm::formatv(Out.Pretty ? "<-- {0:2}\n" : "<-- {0}\n", *Doc));
Sam McCallec109022017-11-28 09:37:43 +0000247 // Finally, execute the action for this JSON message.
248 if (!Dispatcher.call(*Doc, Out))
Ilya Biryukov940901e2017-12-13 12:51:22 +0000249 log(Context::empty(), "JSON dispatch failed!\n");
Sam McCallec109022017-11-28 09:37:43 +0000250 } else {
251 // Parse error. Log the raw message.
Ilya Biryukov940901e2017-12-13 12:51:22 +0000252 log(Context::empty(), "<-- " + JSONRef + "\n");
253 log(Context::empty(), llvm::Twine("JSON parse error: ") +
254 llvm::toString(Doc.takeError()) + "\n");
Sam McCallec109022017-11-28 09:37:43 +0000255 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000256
257 // If we're done, exit the loop.
258 if (IsDone)
259 break;
Ilya Biryukov1fab4f82017-09-04 12:28:15 +0000260 } else {
Ilya Biryukov940901e2017-12-13 12:51:22 +0000261 log(Context::empty(),
262 "Warning: Missing Content-Length header, or message has zero "
263 "length.\n");
Ilya Biryukovafb55542017-05-16 14:40:30 +0000264 }
265 }
266}