blob: 7e0aea5f5166ce52543a02c04720fa61d1d9ce48 [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"
11#include "ProtocolHandlers.h"
12#include "llvm/ADT/SmallString.h"
13#include "llvm/Support/SourceMgr.h"
14#include "llvm/Support/YAMLParser.h"
Ilya Biryukov687b92a2017-05-16 15:23:55 +000015#include <istream>
16
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000017using namespace clang;
18using namespace clangd;
19
Benjamin Kramerd0b2ccd2017-02-10 14:08:40 +000020void JSONOutput::writeMessage(const Twine &Message) {
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000021 llvm::SmallString<128> Storage;
22 StringRef M = Message.toStringRef(Storage);
23
Benjamin Kramerd0b2ccd2017-02-10 14:08:40 +000024 std::lock_guard<std::mutex> Guard(StreamMutex);
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000025 // Log without headers.
26 Logs << "--> " << M << '\n';
27 Logs.flush();
28
29 // Emit message with header.
30 Outs << "Content-Length: " << M.size() << "\r\n\r\n" << M;
31 Outs.flush();
32}
33
Benjamin Kramere14bd422017-02-15 16:44:11 +000034void JSONOutput::log(const Twine &Message) {
35 std::lock_guard<std::mutex> Guard(StreamMutex);
36 Logs << Message;
37 Logs.flush();
38}
39
Ilya Biryukove6dbb582017-10-10 09:08:47 +000040void JSONOutput::mirrorInput(const Twine &Message) {
41 if (!InputMirror)
42 return;
43
44 *InputMirror << Message;
45 InputMirror->flush();
46}
47
Sam McCall8a5dded2017-10-12 13:29:58 +000048void RequestContext::reply(const llvm::Twine &Result) {
49 if (ID.empty()) {
50 Out.log("Attempted to reply to a notification!\n");
51 return;
52 }
53 Out.writeMessage(llvm::Twine(R"({"jsonrpc":"2.0","id":)") + ID +
54 R"(,"result":)" + Result + "}");
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000055}
56
Sam McCall8a5dded2017-10-12 13:29:58 +000057void RequestContext::replyError(int code, const llvm::StringRef &Message) {
58 Out.log("Error " + llvm::Twine(code) + ": " + Message + "\n");
59 if (!ID.empty()) {
60 Out.writeMessage(llvm::Twine(R"({"jsonrpc":"2.0","id":)") + ID +
61 R"(,"error":{"code":)" + llvm::Twine(code) +
62 R"(,"message":")" + llvm::yaml::escape(Message) +
63 R"("}})");
64 }
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000065}
66
Sam McCall8a5dded2017-10-12 13:29:58 +000067void JSONRPCDispatcher::registerHandler(StringRef Method, Handler H) {
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000068 assert(!Handlers.count(Method) && "Handler already registered!");
69 Handlers[Method] = std::move(H);
70}
71
72static void
Sam McCall8a5dded2017-10-12 13:29:58 +000073callHandler(const llvm::StringMap<JSONRPCDispatcher::Handler> &Handlers,
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000074 llvm::yaml::ScalarNode *Method, llvm::yaml::ScalarNode *Id,
Sam McCall8a5dded2017-10-12 13:29:58 +000075 llvm::yaml::MappingNode *Params,
76 const JSONRPCDispatcher::Handler &UnknownHandler, JSONOutput &Out) {
77 llvm::SmallString<64> MethodStorage;
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000078 auto I = Handlers.find(Method->getValue(MethodStorage));
Sam McCall8a5dded2017-10-12 13:29:58 +000079 auto &Handler = I != Handlers.end() ? I->second : UnknownHandler;
80 Handler(RequestContext(Out, Id ? Id->getRawValue() : ""), Params);
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000081}
82
Sam McCall8a5dded2017-10-12 13:29:58 +000083bool JSONRPCDispatcher::call(StringRef Content, JSONOutput &Out) const {
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000084 llvm::SourceMgr SM;
85 llvm::yaml::Stream YAMLStream(Content, SM);
86
87 auto Doc = YAMLStream.begin();
88 if (Doc == YAMLStream.end())
89 return false;
90
91 auto *Root = Doc->getRoot();
92 if (!Root)
93 return false;
94
95 auto *Object = dyn_cast<llvm::yaml::MappingNode>(Root);
96 if (!Object)
97 return false;
98
99 llvm::yaml::ScalarNode *Version = nullptr;
100 llvm::yaml::ScalarNode *Method = nullptr;
101 llvm::yaml::MappingNode *Params = nullptr;
102 llvm::yaml::ScalarNode *Id = nullptr;
103 for (auto &NextKeyValue : *Object) {
104 auto *KeyString = dyn_cast<llvm::yaml::ScalarNode>(NextKeyValue.getKey());
105 if (!KeyString)
106 return false;
107
108 llvm::SmallString<10> KeyStorage;
109 StringRef KeyValue = KeyString->getValue(KeyStorage);
110 llvm::yaml::Node *Value = NextKeyValue.getValue();
111 if (!Value)
112 return false;
113
114 if (KeyValue == "jsonrpc") {
115 // This should be "2.0". Always.
116 Version = dyn_cast<llvm::yaml::ScalarNode>(Value);
117 if (!Version || Version->getRawValue() != "\"2.0\"")
118 return false;
119 } else if (KeyValue == "method") {
120 Method = dyn_cast<llvm::yaml::ScalarNode>(Value);
121 } else if (KeyValue == "id") {
122 Id = dyn_cast<llvm::yaml::ScalarNode>(Value);
123 } else if (KeyValue == "params") {
124 if (!Method)
125 return false;
126 // We have to interleave the call of the function here, otherwise the
127 // YAMLParser will die because it can't go backwards. This is unfortunate
128 // because it will break clients that put the id after params. A possible
129 // fix would be to split the parsing and execution phases.
130 Params = dyn_cast<llvm::yaml::MappingNode>(Value);
Sam McCall8a5dded2017-10-12 13:29:58 +0000131 callHandler(Handlers, Method, Id, Params, UnknownHandler, Out);
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000132 return true;
133 } else {
134 return false;
135 }
136 }
137
138 // In case there was a request with no params, call the handler on the
139 // leftovers.
140 if (!Method)
141 return false;
Sam McCall8a5dded2017-10-12 13:29:58 +0000142 callHandler(Handlers, Method, Id, nullptr, UnknownHandler, Out);
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000143
144 return true;
145}
Ilya Biryukovafb55542017-05-16 14:40:30 +0000146
147void clangd::runLanguageServerLoop(std::istream &In, JSONOutput &Out,
148 JSONRPCDispatcher &Dispatcher,
149 bool &IsDone) {
150 while (In.good()) {
Ilya Biryukov1fab4f82017-09-04 12:28:15 +0000151 // A Language Server Protocol message starts with a set of HTTP headers,
152 // delimited by \r\n, and terminated by an empty line (\r\n).
153 unsigned long long ContentLength = 0;
154 while (In.good()) {
155 std::string Line;
156 std::getline(In, Line);
157 if (!In.good() && errno == EINTR) {
158 In.clear();
159 continue;
160 }
161
Ilya Biryukove6dbb582017-10-10 09:08:47 +0000162 Out.mirrorInput(Line);
163 // Mirror '\n' that gets consumed by std::getline, but is not included in
164 // the resulting Line.
165 // Note that '\r' is part of Line, so we don't need to mirror it
166 // separately.
167 if (!In.eof())
168 Out.mirrorInput("\n");
169
Ilya Biryukov1fab4f82017-09-04 12:28:15 +0000170 llvm::StringRef LineRef(Line);
171
172 // We allow YAML-style comments in headers. Technically this isn't part
173 // of the LSP specification, but makes writing tests easier.
174 if (LineRef.startswith("#"))
175 continue;
176
177 // Content-Type is a specified header, but does nothing.
178 // Content-Length is a mandatory header. It specifies the length of the
179 // following JSON.
180 // It is unspecified what sequence headers must be supplied in, so we
181 // allow any sequence.
182 // The end of headers is signified by an empty line.
183 if (LineRef.consume_front("Content-Length: ")) {
184 if (ContentLength != 0) {
185 Out.log("Warning: Duplicate Content-Length header received. "
Ilya Biryukove6dbb582017-10-10 09:08:47 +0000186 "The previous value for this message (" +
187 std::to_string(ContentLength) + ") was ignored.\n");
Ilya Biryukov1fab4f82017-09-04 12:28:15 +0000188 }
189
190 llvm::getAsUnsignedInteger(LineRef.trim(), 0, ContentLength);
191 continue;
192 } else if (!LineRef.trim().empty()) {
193 // It's another header, ignore it.
194 continue;
195 } else {
196 // An empty line indicates the end of headers.
197 // Go ahead and read the JSON.
198 break;
199 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000200 }
201
Ilya Biryukov1fab4f82017-09-04 12:28:15 +0000202 if (ContentLength > 0) {
203 // Now read the JSON. Insert a trailing null byte as required by the YAML
204 // parser.
205 std::vector<char> JSON(ContentLength + 1, '\0');
206 In.read(JSON.data(), ContentLength);
Ilya Biryukove6dbb582017-10-10 09:08:47 +0000207 Out.mirrorInput(StringRef(JSON.data(), In.gcount()));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000208
Ilya Biryukov1fab4f82017-09-04 12:28:15 +0000209 // If the stream is aborted before we read ContentLength bytes, In
210 // will have eofbit and failbit set.
211 if (!In) {
Ilya Biryukove6dbb582017-10-10 09:08:47 +0000212 Out.log("Input was aborted. Read only " + std::to_string(In.gcount()) +
213 " bytes of expected " + std::to_string(ContentLength) + ".\n");
Ilya Biryukov1fab4f82017-09-04 12:28:15 +0000214 break;
215 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000216
Ilya Biryukov1fab4f82017-09-04 12:28:15 +0000217 llvm::StringRef JSONRef(JSON.data(), ContentLength);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000218 // Log the message.
219 Out.log("<-- " + JSONRef + "\n");
220
221 // Finally, execute the action for this JSON message.
Sam McCall8a5dded2017-10-12 13:29:58 +0000222 if (!Dispatcher.call(JSONRef, Out))
Ilya Biryukovafb55542017-05-16 14:40:30 +0000223 Out.log("JSON dispatch failed!\n");
224
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}