blob: be6be770beb8ac285a2d5012f13acd5b97f89d85 [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"
15using namespace clang;
16using namespace clangd;
17
Benjamin Kramerd0b2ccd2017-02-10 14:08:40 +000018void JSONOutput::writeMessage(const Twine &Message) {
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000019 llvm::SmallString<128> Storage;
20 StringRef M = Message.toStringRef(Storage);
21
Benjamin Kramerd0b2ccd2017-02-10 14:08:40 +000022 std::lock_guard<std::mutex> Guard(StreamMutex);
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000023 // Log without headers.
24 Logs << "--> " << M << '\n';
25 Logs.flush();
26
27 // Emit message with header.
28 Outs << "Content-Length: " << M.size() << "\r\n\r\n" << M;
29 Outs.flush();
30}
31
Benjamin Kramere14bd422017-02-15 16:44:11 +000032void JSONOutput::log(const Twine &Message) {
33 std::lock_guard<std::mutex> Guard(StreamMutex);
34 Logs << Message;
35 Logs.flush();
36}
37
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000038void Handler::handleMethod(llvm::yaml::MappingNode *Params, StringRef ID) {
Benjamin Kramere14bd422017-02-15 16:44:11 +000039 Output.log("Method ignored.\n");
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000040 // Return that this method is unsupported.
41 writeMessage(
42 R"({"jsonrpc":"2.0","id":)" + ID +
43 R"(,"error":{"code":-32601}})");
44}
45
46void Handler::handleNotification(llvm::yaml::MappingNode *Params) {
Benjamin Kramere14bd422017-02-15 16:44:11 +000047 Output.log("Notification ignored.\n");
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000048}
49
50void JSONRPCDispatcher::registerHandler(StringRef Method,
51 std::unique_ptr<Handler> H) {
52 assert(!Handlers.count(Method) && "Handler already registered!");
53 Handlers[Method] = std::move(H);
54}
55
56static void
57callHandler(const llvm::StringMap<std::unique_ptr<Handler>> &Handlers,
58 llvm::yaml::ScalarNode *Method, llvm::yaml::ScalarNode *Id,
59 llvm::yaml::MappingNode *Params, Handler *UnknownHandler) {
60 llvm::SmallString<10> MethodStorage;
61 auto I = Handlers.find(Method->getValue(MethodStorage));
62 auto *Handler = I != Handlers.end() ? I->second.get() : UnknownHandler;
63 if (Id)
64 Handler->handleMethod(Params, Id->getRawValue());
65 else
66 Handler->handleNotification(Params);
67}
68
69bool JSONRPCDispatcher::call(StringRef Content) const {
70 llvm::SourceMgr SM;
71 llvm::yaml::Stream YAMLStream(Content, SM);
72
73 auto Doc = YAMLStream.begin();
74 if (Doc == YAMLStream.end())
75 return false;
76
77 auto *Root = Doc->getRoot();
78 if (!Root)
79 return false;
80
81 auto *Object = dyn_cast<llvm::yaml::MappingNode>(Root);
82 if (!Object)
83 return false;
84
85 llvm::yaml::ScalarNode *Version = nullptr;
86 llvm::yaml::ScalarNode *Method = nullptr;
87 llvm::yaml::MappingNode *Params = nullptr;
88 llvm::yaml::ScalarNode *Id = nullptr;
89 for (auto &NextKeyValue : *Object) {
90 auto *KeyString = dyn_cast<llvm::yaml::ScalarNode>(NextKeyValue.getKey());
91 if (!KeyString)
92 return false;
93
94 llvm::SmallString<10> KeyStorage;
95 StringRef KeyValue = KeyString->getValue(KeyStorage);
96 llvm::yaml::Node *Value = NextKeyValue.getValue();
97 if (!Value)
98 return false;
99
100 if (KeyValue == "jsonrpc") {
101 // This should be "2.0". Always.
102 Version = dyn_cast<llvm::yaml::ScalarNode>(Value);
103 if (!Version || Version->getRawValue() != "\"2.0\"")
104 return false;
105 } else if (KeyValue == "method") {
106 Method = dyn_cast<llvm::yaml::ScalarNode>(Value);
107 } else if (KeyValue == "id") {
108 Id = dyn_cast<llvm::yaml::ScalarNode>(Value);
109 } else if (KeyValue == "params") {
110 if (!Method)
111 return false;
112 // We have to interleave the call of the function here, otherwise the
113 // YAMLParser will die because it can't go backwards. This is unfortunate
114 // because it will break clients that put the id after params. A possible
115 // fix would be to split the parsing and execution phases.
116 Params = dyn_cast<llvm::yaml::MappingNode>(Value);
117 callHandler(Handlers, Method, Id, Params, UnknownHandler.get());
118 return true;
119 } else {
120 return false;
121 }
122 }
123
124 // In case there was a request with no params, call the handler on the
125 // leftovers.
126 if (!Method)
127 return false;
128 callHandler(Handlers, Method, Id, nullptr, UnknownHandler.get());
129
130 return true;
131}
Ilya Biryukovafb55542017-05-16 14:40:30 +0000132
133void clangd::runLanguageServerLoop(std::istream &In, JSONOutput &Out,
134 JSONRPCDispatcher &Dispatcher,
135 bool &IsDone) {
136 while (In.good()) {
137 // A Language Server Protocol message starts with a HTTP header, delimited
138 // by \r\n.
139 std::string Line;
140 std::getline(In, Line);
141 if (!In.good() && errno == EINTR) {
142 In.clear();
143 continue;
144 }
145
146 // Skip empty lines.
147 llvm::StringRef LineRef(Line);
148 if (LineRef.trim().empty())
149 continue;
150
151 // We allow YAML-style comments. Technically this isn't part of the
152 // LSP specification, but makes writing tests easier.
153 if (LineRef.startswith("#"))
154 continue;
155
156 unsigned long long Len = 0;
157 // FIXME: 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 if (LineRef.consume_front("Content-Length: "))
161 llvm::getAsUnsignedInteger(LineRef.trim(), 0, Len);
162
163 // Check if the next line only contains \r\n. If not this is another header,
164 // which we ignore.
165 char NewlineBuf[2];
166 In.read(NewlineBuf, 2);
167 if (std::memcmp(NewlineBuf, "\r\n", 2) != 0)
168 continue;
169
170 // Now read the JSON. Insert a trailing null byte as required by the YAML
171 // parser.
172 std::vector<char> JSON(Len + 1, '\0');
173 In.read(JSON.data(), Len);
174
175 if (Len > 0) {
176 llvm::StringRef JSONRef(JSON.data(), Len);
177 // Log the message.
178 Out.log("<-- " + JSONRef + "\n");
179
180 // Finally, execute the action for this JSON message.
181 if (!Dispatcher.call(JSONRef))
182 Out.log("JSON dispatch failed!\n");
183
184 // If we're done, exit the loop.
185 if (IsDone)
186 break;
187 }
188 }
189}