blob: 5deb75aad31d4e75cc26311dec7db9fda3ee7586 [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()) {
139 // A Language Server Protocol message starts with a HTTP header, delimited
140 // by \r\n.
141 std::string Line;
142 std::getline(In, Line);
143 if (!In.good() && errno == EINTR) {
144 In.clear();
145 continue;
146 }
147
148 // Skip empty lines.
149 llvm::StringRef LineRef(Line);
150 if (LineRef.trim().empty())
151 continue;
152
153 // We allow YAML-style comments. Technically this isn't part of the
154 // LSP specification, but makes writing tests easier.
155 if (LineRef.startswith("#"))
156 continue;
157
158 unsigned long long Len = 0;
159 // FIXME: 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 if (LineRef.consume_front("Content-Length: "))
163 llvm::getAsUnsignedInteger(LineRef.trim(), 0, Len);
164
165 // Check if the next line only contains \r\n. If not this is another header,
166 // which we ignore.
167 char NewlineBuf[2];
168 In.read(NewlineBuf, 2);
169 if (std::memcmp(NewlineBuf, "\r\n", 2) != 0)
170 continue;
171
172 // Now read the JSON. Insert a trailing null byte as required by the YAML
173 // parser.
174 std::vector<char> JSON(Len + 1, '\0');
175 In.read(JSON.data(), Len);
176
177 if (Len > 0) {
178 llvm::StringRef JSONRef(JSON.data(), Len);
179 // Log the message.
180 Out.log("<-- " + JSONRef + "\n");
181
182 // Finally, execute the action for this JSON message.
183 if (!Dispatcher.call(JSONRef))
184 Out.log("JSON dispatch failed!\n");
185
186 // If we're done, exit the loop.
187 if (IsDone)
188 break;
189 }
190 }
191}