blob: 29dc50c6621809d77dd9c01f7110112cf4405213 [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
Sam McCalldd0566b2017-11-06 15:40:30 +000022void JSONOutput::writeMessage(const json::Expr &Message) {
23 std::string S;
24 llvm::raw_string_ostream OS(S);
25 if (Pretty)
26 OS << llvm::formatv("{0:2}", Message);
27 else
28 OS << Message;
29 OS.flush();
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000030
Benjamin Kramerd0b2ccd2017-02-10 14:08:40 +000031 std::lock_guard<std::mutex> Guard(StreamMutex);
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000032 // Log without headers.
Sam McCalldd0566b2017-11-06 15:40:30 +000033 Logs << "--> " << S << '\n';
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000034 Logs.flush();
35
36 // Emit message with header.
Sam McCalldd0566b2017-11-06 15:40:30 +000037 Outs << "Content-Length: " << S.size() << "\r\n\r\n" << S;
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000038 Outs.flush();
39}
40
Benjamin Kramere14bd422017-02-15 16:44:11 +000041void JSONOutput::log(const Twine &Message) {
Sam McCall8567cb32017-11-02 09:21:51 +000042 trace::log(Message);
Benjamin Kramere14bd422017-02-15 16:44:11 +000043 std::lock_guard<std::mutex> Guard(StreamMutex);
44 Logs << Message;
45 Logs.flush();
46}
47
Ilya Biryukove6dbb582017-10-10 09:08:47 +000048void JSONOutput::mirrorInput(const Twine &Message) {
49 if (!InputMirror)
50 return;
51
52 *InputMirror << Message;
53 InputMirror->flush();
54}
55
Sam McCalldd0566b2017-11-06 15:40:30 +000056void RequestContext::reply(json::Expr &&Result) {
57 if (!ID) {
Sam McCall8a5dded2017-10-12 13:29:58 +000058 Out.log("Attempted to reply to a notification!\n");
59 return;
60 }
Sam McCall9cfd9c92017-11-23 17:12:04 +000061 SPAN_ATTACH(tracer(), "Reply", Result);
Sam McCalldd0566b2017-11-06 15:40:30 +000062 Out.writeMessage(json::obj{
63 {"jsonrpc", "2.0"},
64 {"id", *ID},
65 {"result", std::move(Result)},
66 });
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000067}
68
Ilya Biryukov9e11c4c2017-11-15 18:04:56 +000069void RequestContext::replyError(ErrorCode code,
70 const llvm::StringRef &Message) {
Haojian Wu2375c922017-11-07 10:21:02 +000071 Out.log("Error " + Twine(static_cast<int>(code)) + ": " + Message + "\n");
Sam McCall9cfd9c92017-11-23 17:12:04 +000072 SPAN_ATTACH(tracer(), "Error",
73 (json::obj{{"code", static_cast<int>(code)},
74 {"message", Message.str()}}));
Sam McCalldd0566b2017-11-06 15:40:30 +000075 if (ID) {
76 Out.writeMessage(json::obj{
77 {"jsonrpc", "2.0"},
78 {"id", *ID},
Ilya Biryukov9e11c4c2017-11-15 18:04:56 +000079 {"error",
80 json::obj{{"code", static_cast<int>(code)}, {"message", Message}}},
Sam McCalldd0566b2017-11-06 15:40:30 +000081 });
Sam McCall8a5dded2017-10-12 13:29:58 +000082 }
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000083}
84
Sam McCalldd0566b2017-11-06 15:40:30 +000085void RequestContext::call(StringRef Method, json::Expr &&Params) {
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +000086 // FIXME: Generate/Increment IDs for every request so that we can get proper
87 // replies once we need to.
Sam McCall9cfd9c92017-11-23 17:12:04 +000088 SPAN_ATTACH(tracer(), "Call",
89 (json::obj{{"method", Method.str()}, {"params", Params}}));
Sam McCalldd0566b2017-11-06 15:40:30 +000090 Out.writeMessage(json::obj{
91 {"jsonrpc", "2.0"},
92 {"id", 1},
93 {"method", Method},
94 {"params", std::move(Params)},
95 });
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +000096}
97
Sam McCall8a5dded2017-10-12 13:29:58 +000098void JSONRPCDispatcher::registerHandler(StringRef Method, Handler H) {
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000099 assert(!Handlers.count(Method) && "Handler already registered!");
100 Handlers[Method] = std::move(H);
101}
102
Sam McCallec109022017-11-28 09:37:43 +0000103bool JSONRPCDispatcher::call(const json::Expr &Message, JSONOutput &Out) const {
104 // Message must be an object with "jsonrpc":"2.0".
105 auto *Object = Message.asObject();
106 if (!Object || Object->getString("jsonrpc") != Optional<StringRef>("2.0"))
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000107 return false;
Sam McCallec109022017-11-28 09:37:43 +0000108 // ID may be any JSON value. If absent, this is a notification.
Sam McCalldd0566b2017-11-06 15:40:30 +0000109 llvm::Optional<json::Expr> ID;
Sam McCallec109022017-11-28 09:37:43 +0000110 if (auto *I = Object->get("id"))
111 ID = std::move(*I);
112 // Method must be given.
113 auto Method = Object->getString("method");
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000114 if (!Method)
115 return false;
Sam McCallec109022017-11-28 09:37:43 +0000116 // Params should be given, use null if not.
117 json::Expr Params = nullptr;
118 if (auto *P = Object->get("params"))
119 Params = std::move(*P);
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000120
Sam McCallec109022017-11-28 09:37:43 +0000121 auto I = Handlers.find(*Method);
122 auto &Handler = I != Handlers.end() ? I->second : UnknownHandler;
123 RequestContext Ctx(Out, *Method, std::move(ID));
124 SPAN_ATTACH(Ctx.tracer(), "Params", Params);
125 Handler(std::move(Ctx), std::move(Params));
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000126 return true;
127}
Ilya Biryukovafb55542017-05-16 14:40:30 +0000128
129void clangd::runLanguageServerLoop(std::istream &In, JSONOutput &Out,
130 JSONRPCDispatcher &Dispatcher,
131 bool &IsDone) {
132 while (In.good()) {
Ilya Biryukov1fab4f82017-09-04 12:28:15 +0000133 // A Language Server Protocol message starts with a set of HTTP headers,
134 // delimited by \r\n, and terminated by an empty line (\r\n).
135 unsigned long long ContentLength = 0;
136 while (In.good()) {
137 std::string Line;
138 std::getline(In, Line);
139 if (!In.good() && errno == EINTR) {
140 In.clear();
141 continue;
142 }
143
Ilya Biryukove6dbb582017-10-10 09:08:47 +0000144 Out.mirrorInput(Line);
145 // Mirror '\n' that gets consumed by std::getline, but is not included in
146 // the resulting Line.
147 // Note that '\r' is part of Line, so we don't need to mirror it
148 // separately.
149 if (!In.eof())
150 Out.mirrorInput("\n");
151
Ilya Biryukov1fab4f82017-09-04 12:28:15 +0000152 llvm::StringRef LineRef(Line);
153
Sam McCallec109022017-11-28 09:37:43 +0000154 // We allow comments in headers. Technically this isn't part
Ilya Biryukov1fab4f82017-09-04 12:28:15 +0000155 // of the LSP specification, but makes writing tests easier.
156 if (LineRef.startswith("#"))
157 continue;
158
159 // Content-Type is a specified header, but does nothing.
160 // Content-Length is a mandatory header. It specifies the length of the
161 // following JSON.
162 // It is unspecified what sequence headers must be supplied in, so we
163 // allow any sequence.
164 // The end of headers is signified by an empty line.
165 if (LineRef.consume_front("Content-Length: ")) {
166 if (ContentLength != 0) {
167 Out.log("Warning: Duplicate Content-Length header received. "
Ilya Biryukove6dbb582017-10-10 09:08:47 +0000168 "The previous value for this message (" +
169 std::to_string(ContentLength) + ") was ignored.\n");
Ilya Biryukov1fab4f82017-09-04 12:28:15 +0000170 }
171
172 llvm::getAsUnsignedInteger(LineRef.trim(), 0, ContentLength);
173 continue;
174 } else if (!LineRef.trim().empty()) {
175 // It's another header, ignore it.
176 continue;
177 } else {
178 // An empty line indicates the end of headers.
179 // Go ahead and read the JSON.
180 break;
181 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000182 }
183
Benjamin Kramer1d053792017-10-27 17:06:41 +0000184 // Guard against large messages. This is usually a bug in the client code
185 // and we don't want to crash downstream because of it.
186 if (ContentLength > 1 << 30) { // 1024M
187 In.ignore(ContentLength);
188 Out.log("Skipped overly large message of " + Twine(ContentLength) +
189 " bytes.\n");
190 continue;
191 }
192
Ilya Biryukov1fab4f82017-09-04 12:28:15 +0000193 if (ContentLength > 0) {
Sam McCallec109022017-11-28 09:37:43 +0000194 std::vector<char> JSON(ContentLength);
Sam McCall8567cb32017-11-02 09:21:51 +0000195 llvm::StringRef JSONRef;
196 {
Sam McCall8567cb32017-11-02 09:21:51 +0000197 In.read(JSON.data(), ContentLength);
198 Out.mirrorInput(StringRef(JSON.data(), In.gcount()));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000199
Sam McCall8567cb32017-11-02 09:21:51 +0000200 // If the stream is aborted before we read ContentLength bytes, In
201 // will have eofbit and failbit set.
202 if (!In) {
203 Out.log("Input was aborted. Read only " +
204 std::to_string(In.gcount()) + " bytes of expected " +
205 std::to_string(ContentLength) + ".\n");
206 break;
207 }
208
209 JSONRef = StringRef(JSON.data(), ContentLength);
Ilya Biryukov1fab4f82017-09-04 12:28:15 +0000210 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000211
Sam McCallec109022017-11-28 09:37:43 +0000212 if (auto Doc = json::parse(JSONRef)) {
213 // Log the formatted message.
214 Out.log(llvm::formatv(Out.Pretty ? "<-- {0:2}\n" : "<-- {0}\n", *Doc));
215 // Finally, execute the action for this JSON message.
216 if (!Dispatcher.call(*Doc, Out))
217 Out.log("JSON dispatch failed!\n");
218 } else {
219 // Parse error. Log the raw message.
220 Out.log("<-- " + JSONRef + "\n");
221 Out.log(llvm::Twine("JSON parse error: ") +
222 llvm::toString(Doc.takeError()) + "\n");
223 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000224
225 // If we're done, exit the loop.
226 if (IsDone)
227 break;
Ilya Biryukov1fab4f82017-09-04 12:28:15 +0000228 } else {
Ilya Biryukove6dbb582017-10-10 09:08:47 +0000229 Out.log("Warning: Missing Content-Length header, or message has zero "
230 "length.\n");
Ilya Biryukovafb55542017-05-16 14:40:30 +0000231 }
232 }
233}