|
| 1 | +import json |
| 2 | +import logging |
| 3 | + |
| 4 | +from tornado import web, ioloop, websocket |
| 5 | + |
| 6 | +from jsonrpc import dispatchers, endpoint |
| 7 | + |
| 8 | +log = logging.getLogger(__name__) |
| 9 | + |
| 10 | + |
| 11 | +class LanguageServer(dispatchers.MethodDispatcher): |
| 12 | + """Implement a JSON RPC method dispatcher for the language server protocol.""" |
| 13 | + |
| 14 | + def __init__(self): |
| 15 | + # Endpoint is lazily set after construction |
| 16 | + self.endpoint = None |
| 17 | + |
| 18 | + def m_initialize(self, rootUri=None, **kwargs): |
| 19 | + log.info("Got initialize params: %s", kwargs) |
| 20 | + return {"capabilities": { |
| 21 | + "textDocumentSync": { |
| 22 | + "openClose": True, |
| 23 | + } |
| 24 | + }} |
| 25 | + |
| 26 | + def m_text_document__did_open(self, textDocument=None, **_kwargs): |
| 27 | + log.info("Opened text document %s", textDocument) |
| 28 | + self.endpoint.notify('textDocument/publishDiagnostics', { |
| 29 | + 'uri': textDocument['uri'], |
| 30 | + 'diagnostics': [{ |
| 31 | + 'range': { |
| 32 | + 'start': {'line': 0, 'character': 0}, |
| 33 | + 'end': {'line': 1, 'character': 0}, |
| 34 | + }, |
| 35 | + 'message': 'Some very bad Python code', |
| 36 | + 'severity': 1 # DiagnosticSeverity.Error |
| 37 | + }] |
| 38 | + }) |
| 39 | + |
| 40 | + |
| 41 | +class LanguageServerWebSocketHandler(websocket.WebSocketHandler): |
| 42 | + """Setup tornado websocket handler to host language server.""" |
| 43 | + |
| 44 | + def __init__(self, *args, **kwargs): |
| 45 | + # Create an instance of the language server used to dispatch JSON RPC methods |
| 46 | + langserver = LanguageServer() |
| 47 | + |
| 48 | + # Setup an endpoint that dispatches to the ls, and writes server->client messages |
| 49 | + # back to the client websocket |
| 50 | + self.endpoint = endpoint.Endpoint(langserver, lambda msg: self.write_message(json.dumps(msg))) |
| 51 | + |
| 52 | + # Give the language server a handle to the endpoint so it can send JSON RPC |
| 53 | + # notifications and requests. |
| 54 | + langserver.endpoint = self.endpoint |
| 55 | + |
| 56 | + super(LanguageServerWebSocketHandler, self).__init__(*args, **kwargs) |
| 57 | + |
| 58 | + def on_message(self, message): |
| 59 | + """Forward client->server messages to the endpoint.""" |
| 60 | + self.endpoint.consume(json.loads(message)) |
| 61 | + |
| 62 | + def check_origin(self, origin): |
| 63 | + return True |
| 64 | + |
| 65 | + |
| 66 | +if __name__ == "__main__": |
| 67 | + app = web.Application([ |
| 68 | + (r"/python", LanguageServerWebSocketHandler), |
| 69 | + ]) |
| 70 | + app.listen(3000, address='127.0.0.1') |
| 71 | + ioloop.IOLoop.current().start() |
0 commit comments