1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
|
import os
from pathlib import Path
import logging
import json
from urllib.parse import unquote, urlparse
log = logging.getLogger("ghdl-ls")
is_windows = os.name == "nt"
class ProtocolError(Exception):
pass
class LSPConn:
def __init__(self, reader, writer):
self.reader = reader
self.writer = writer
def readline(self):
data = self.reader.readline()
return data.decode("utf-8")
def read(self, size):
data = self.reader.read(size)
return data.decode("utf-8")
def write(self, out):
self.writer.write(out.encode())
self.writer.flush()
def path_from_uri(uri):
# Convert file uri to path (strip html like head part)
# This is needed to get the root path and to load a document when the
# textual source is not present.
if not uri.startswith("file://"):
# No scheme
return uri
path = unquote(urlparse(uri).path)
# On windows, absolute files start like "/C:/aa/bbb".
# Remove the first "/".
if is_windows:
path = path[1:]
# Path.resolve used to ensure consistent capitalization
# on Windows, as GHDL-ada will fail if it is inconsistent.
return Path(path).resolve().as_posix()
def path_to_uri(path):
return Path(path).resolve().as_uri()
def normalize_rpc_file_uris(rpc):
# Normalize all file URIs inside an RPC to have consistent capitalization.
# Fixes a crash on windows where the underlying ada crashes
# if paths to the same file are given with inconsistent
# capitalization.
for key, val in rpc.items():
# recurse into all leaf elements.
if isinstance(val, dict):
normalize_rpc_file_uris(val)
elif key == "rootUri" or key == "uri":
# normalize URI
rpc[key] = path_to_uri(path_from_uri(val))
class LanguageProtocolServer(object):
def __init__(self, handler, conn):
self.conn = conn
self.handler = handler
if handler is not None:
handler.set_lsp(self)
self.running = True
self._next_id = 0
def read_request(self):
headers = {}
while True:
# Read a line
line = self.conn.readline()
# Return on EOF.
if not line:
return None
if line[-2:] != "\r\n":
raise ProtocolError("invalid end of line in header")
line = line[:-2]
if not line:
# End of headers.
log.debug("Headers: %r", headers)
length = headers.get("Content-Length", None)
if length is not None:
body = self.conn.read(int(length))
return body
else:
raise ProtocolError("missing Content-Length in header")
else:
key, value = line.split(": ", 1)
headers[key] = value
def run(self):
while self.running:
body = self.read_request()
if body is None:
# EOF
break
# Text to JSON
msg = json.loads(body)
log.debug("Read msg: %s", msg)
reply = self.handle(msg)
if reply is not None:
self.write_output(reply)
def handle(self, msg):
if msg.get("jsonrpc", None) != "2.0":
raise ProtocolError("invalid jsonrpc version")
tid = msg.get("id", None)
method = msg.get("method", None)
if method is None:
# This is a reply.
log.error("Unexpected reply for %s", tid)
return
params = msg.get("params", None)
# Fix capitalization issues on windows.
if is_windows:
normalize_rpc_file_uris(msg)
fmethod = self.handler.dispatcher.get(method, None)
if fmethod:
if params is None:
params = {}
try:
response = fmethod(**params)
except Exception:
log.exception("Caught exception while handling %s with params %s:", method, params)
self.show_message(
MessageType.Error,
f"Caught exception while handling {method}, see VHDL language server output for details.",
)
response = None
if tid is None:
# If this was just a notification, discard it
return None
log.debug("Response: %s", response)
rbody = {
"jsonrpc": "2.0",
"id": tid,
"result": response,
}
else:
# Unknown method.
log.error("Unknown method %s", method)
# If this was just a notification, discard it
if tid is None:
return None
# Otherwise create an error.
rbody = {
"jsonrpc": "2.0",
"id": tid,
"error": {
"code": JSONErrorCodes.MethodNotFound,
"message": f"unknown method {method}",
},
}
return rbody
def write_output(self, body):
output = json.dumps(body, separators=(",", ":"))
self.conn.write(f"Content-Length: {len(output)}\r\n")
self.conn.write("\r\n")
self.conn.write(output)
def notify(self, method, params):
"""Send a notification."""
body = {
"jsonrpc": "2.0",
"method": method,
"params": params,
}
self.write_output(body)
def send_request(self, method, params):
"""Send a request."""
self._next_id += 1
body = {
"jsonrpc": "2.0",
"id": self._next_id,
"method": method,
"params": params,
}
self.write_output(body)
def shutdown(self):
"""Prepare to shutdown the server."""
self.running = False
def show_message(self, typ, message):
self.notify("window/showMessage", {"type": typ, "message": message})
def configuration(self, items):
return self.send_request("workspace/configuration", {"items": items})
# ----------------------------------------------------------------------
# Standard defines and object types
#
class JSONErrorCodes(object):
# Defined by JSON RPC
ParseError = -32700
InvalidRequest = -32600
MethodNotFound = -32601
InvalidParams = -32602
InternalError = -32603
serverErrorStart = -32099
serverErrorEnd = -32000
ServerNotInitialized = -32002
UnknownErrorCode = -32001
# Defined by the protocol.
RequestCancelled = -32800
ContentModified = -32801
class CompletionKind(object):
Text = 1
Method = 2
Function = 3
Constructor = 4
Field = 5
Variable = 6
Class = 7
Interface = 8
Module = 9
Property = 10
Unit = 11
Value = 12
Enum = 13
Keyword = 14
Snippet = 15
Color = 16
File = 17
Reference = 18
class DiagnosticSeverity(object):
Error = 1
Warning = 2
Information = 3
Hint = 4
class TextDocumentSyncKind(object):
NONE = (0,)
FULL = 1
INCREMENTAL = 2
class MessageType(object):
Error = 1
Warning = 2
Info = 3
Log = 4
class SymbolKind(object):
File = 1
Module = 2
Namespace = 3
Package = 4
Class = 5
Method = 6
Property = 7
Field = 8
Constructor = 9
Enum = 10
Interface = 11
Function = 12
Variable = 13
Constant = 14
String = 15
Number = 16
Boolean = 17
Array = 18
|