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