blob: 979402c03901b613a737da3ae9d71498b98a6086 [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
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000048void Handler::handleMethod(llvm::yaml::MappingNode *Params, StringRef ID) {
Benjamin Kramere14bd422017-02-15 16:44:11 +000049 Output.log("Method ignored.\n");
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000050 // Return that this method is unsupported.
51 writeMessage(
52 R"({"jsonrpc":"2.0","id":)" + ID +
Benjamin Kramer9297af62017-09-25 17:16:47 +000053 R"(,"error":{"code":-32601,"message":"method not found"}})");
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000054}
55
56void Handler::handleNotification(llvm::yaml::MappingNode *Params) {
Benjamin Kramere14bd422017-02-15 16:44:11 +000057 Output.log("Notification ignored.\n");
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000058}
59
60void JSONRPCDispatcher::registerHandler(StringRef Method,
61 std::unique_ptr<Handler> H) {
62 assert(!Handlers.count(Method) && "Handler already registered!");
63 Handlers[Method] = std::move(H);
64}
65
66static void
67callHandler(const llvm::StringMap<std::unique_ptr<Handler>> &Handlers,
68 llvm::yaml::ScalarNode *Method, llvm::yaml::ScalarNode *Id,
69 llvm::yaml::MappingNode *Params, Handler *UnknownHandler) {
70 llvm::SmallString<10> MethodStorage;
71 auto I = Handlers.find(Method->getValue(MethodStorage));
72 auto *Handler = I != Handlers.end() ? I->second.get() : UnknownHandler;
73 if (Id)
74 Handler->handleMethod(Params, Id->getRawValue());
75 else
76 Handler->handleNotification(Params);
77}
78
79bool JSONRPCDispatcher::call(StringRef Content) const {
80 llvm::SourceMgr SM;
81 llvm::yaml::Stream YAMLStream(Content, SM);
82
83 auto Doc = YAMLStream.begin();
84 if (Doc == YAMLStream.end())
85 return false;
86
87 auto *Root = Doc->getRoot();
88 if (!Root)
89 return false;
90
91 auto *Object = dyn_cast<llvm::yaml::MappingNode>(Root);
92 if (!Object)
93 return false;
94
95 llvm::yaml::ScalarNode *Version = nullptr;
96 llvm::yaml::ScalarNode *Method = nullptr;
97 llvm::yaml::MappingNode *Params = nullptr;
98 llvm::yaml::ScalarNode *Id = nullptr;
99 for (auto &NextKeyValue : *Object) {
100 auto *KeyString = dyn_cast<llvm::yaml::ScalarNode>(NextKeyValue.getKey());
101 if (!KeyString)
102 return false;
103
104 llvm::SmallString<10> KeyStorage;
105 StringRef KeyValue = KeyString->getValue(KeyStorage);
106 llvm::yaml::Node *Value = NextKeyValue.getValue();
107 if (!Value)
108 return false;
109
110 if (KeyValue == "jsonrpc") {
111 // This should be "2.0". Always.
112 Version = dyn_cast<llvm::yaml::ScalarNode>(Value);
113 if (!Version || Version->getRawValue() != "\"2.0\"")
114 return false;
115 } else if (KeyValue == "method") {
116 Method = dyn_cast<llvm::yaml::ScalarNode>(Value);
117 } else if (KeyValue == "id") {
118 Id = dyn_cast<llvm::yaml::ScalarNode>(Value);
119 } else if (KeyValue == "params") {
120 if (!Method)
121 return false;
122 // We have to interleave the call of the function here, otherwise the
123 // YAMLParser will die because it can't go backwards. This is unfortunate
124 // because it will break clients that put the id after params. A possible
125 // fix would be to split the parsing and execution phases.
126 Params = dyn_cast<llvm::yaml::MappingNode>(Value);
127 callHandler(Handlers, Method, Id, Params, UnknownHandler.get());
128 return true;
129 } else {
130 return false;
131 }
132 }
133
134 // In case there was a request with no params, call the handler on the
135 // leftovers.
136 if (!Method)
137 return false;
138 callHandler(Handlers, Method, Id, nullptr, UnknownHandler.get());
139
140 return true;
141}
Ilya Biryukovafb55542017-05-16 14:40:30 +0000142
143void clangd::runLanguageServerLoop(std::istream &In, JSONOutput &Out,
144 JSONRPCDispatcher &Dispatcher,
145 bool &IsDone) {
146 while (In.good()) {
Ilya Biryukov1fab4f82017-09-04 12:28:15 +0000147 // A Language Server Protocol message starts with a set of HTTP headers,
148 // delimited by \r\n, and terminated by an empty line (\r\n).
149 unsigned long long ContentLength = 0;
150 while (In.good()) {
151 std::string Line;
152 std::getline(In, Line);
153 if (!In.good() && errno == EINTR) {
154 In.clear();
155 continue;
156 }
157
Ilya Biryukove6dbb582017-10-10 09:08:47 +0000158 Out.mirrorInput(Line);
159 // Mirror '\n' that gets consumed by std::getline, but is not included in
160 // the resulting Line.
161 // Note that '\r' is part of Line, so we don't need to mirror it
162 // separately.
163 if (!In.eof())
164 Out.mirrorInput("\n");
165
Ilya Biryukov1fab4f82017-09-04 12:28:15 +0000166 llvm::StringRef LineRef(Line);
167
168 // We allow YAML-style comments in headers. Technically this isn't part
169 // of the LSP specification, but makes writing tests easier.
170 if (LineRef.startswith("#"))
171 continue;
172
173 // Content-Type is a specified header, but does nothing.
174 // Content-Length is a mandatory header. It specifies the length of the
175 // following JSON.
176 // It is unspecified what sequence headers must be supplied in, so we
177 // allow any sequence.
178 // The end of headers is signified by an empty line.
179 if (LineRef.consume_front("Content-Length: ")) {
180 if (ContentLength != 0) {
181 Out.log("Warning: Duplicate Content-Length header received. "
Ilya Biryukove6dbb582017-10-10 09:08:47 +0000182 "The previous value for this message (" +
183 std::to_string(ContentLength) + ") was ignored.\n");
Ilya Biryukov1fab4f82017-09-04 12:28:15 +0000184 }
185
186 llvm::getAsUnsignedInteger(LineRef.trim(), 0, ContentLength);
187 continue;
188 } else if (!LineRef.trim().empty()) {
189 // It's another header, ignore it.
190 continue;
191 } else {
192 // An empty line indicates the end of headers.
193 // Go ahead and read the JSON.
194 break;
195 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000196 }
197
Ilya Biryukov1fab4f82017-09-04 12:28:15 +0000198 if (ContentLength > 0) {
199 // Now read the JSON. Insert a trailing null byte as required by the YAML
200 // parser.
201 std::vector<char> JSON(ContentLength + 1, '\0');
202 In.read(JSON.data(), ContentLength);
Ilya Biryukove6dbb582017-10-10 09:08:47 +0000203 Out.mirrorInput(StringRef(JSON.data(), In.gcount()));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000204
Ilya Biryukov1fab4f82017-09-04 12:28:15 +0000205 // If the stream is aborted before we read ContentLength bytes, In
206 // will have eofbit and failbit set.
207 if (!In) {
Ilya Biryukove6dbb582017-10-10 09:08:47 +0000208 Out.log("Input was aborted. Read only " + std::to_string(In.gcount()) +
209 " bytes of expected " + std::to_string(ContentLength) + ".\n");
Ilya Biryukov1fab4f82017-09-04 12:28:15 +0000210 break;
211 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000212
Ilya Biryukov1fab4f82017-09-04 12:28:15 +0000213 llvm::StringRef JSONRef(JSON.data(), ContentLength);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000214 // Log the message.
215 Out.log("<-- " + JSONRef + "\n");
216
217 // Finally, execute the action for this JSON message.
218 if (!Dispatcher.call(JSONRef))
219 Out.log("JSON dispatch failed!\n");
220
221 // If we're done, exit the loop.
222 if (IsDone)
223 break;
Ilya Biryukov1fab4f82017-09-04 12:28:15 +0000224 } else {
Ilya Biryukove6dbb582017-10-10 09:08:47 +0000225 Out.log("Warning: Missing Content-Length header, or message has zero "
226 "length.\n");
Ilya Biryukovafb55542017-05-16 14:40:30 +0000227 }
228 }
229}