import argparse
import json
import os
import select
import subprocess
import tempfile
from pathlib import Path
def event(method, params=None, request_id=None):
message = {"jsonrpc": "2.0", "method": method}
if params is not None:
message["params"] = params
if request_id is not None:
message["id"] = request_id
return message
def send(proc, message):
body = json.dumps(message, ensure_ascii=False).encode()
proc.stdin.write(f"Content-Length: {len(body)}\r\n\r\n".encode() + body)
proc.stdin.flush()
def receive(proc):
def read(size):
data = bytearray()
while len(data) < size:
if not select.select([proc.stdout], [], [], 10)[0]:
raise TimeoutError("waiting for a proxy response")
block = os.read(proc.stdout.fileno(), size - len(data))
if not block:
raise EOFError("proxy closed before its response")
data.extend(block)
return bytes(data)
headers = bytearray()
while not headers.endswith(b"\r\n\r\n"):
headers.extend(read(1))
name, length = headers.strip().split(b": ")
assert name == b"Content-Length"
return json.loads(read(int(length)))
def receive_reply(proc, request_id):
while True:
reply = receive(proc)
if reply.get("method") == "textDocument/publishDiagnostics":
continue
if reply.get("method") == "workspace/diagnostic/refresh":
send(proc, {"jsonrpc": "2.0", "id": reply["id"], "result": None})
continue
assert reply.get("id") == request_id, reply
return reply
def edit(start_line, start_col, end_line, end_col, text):
return {
"range": {
"start": {"line": start_line, "character": start_col},
"end": {"line": end_line, "character": end_col},
},
"text": text,
}
def at(line, character):
return {"line": line, "character": character}
def span(line, start, end):
return {"start": at(line, start), "end": at(line, end)}
def navigate(proc, uri):
navigation = Path("tests/fixtures/navigation.el").resolve()
nav_uri = navigation.as_uri()
doc = {"uri": nav_uri}
send(
proc,
event(
"textDocument/didOpen",
{
"textDocument": {
"uri": nav_uri,
"languageId": "emacs-lisp",
"version": 1,
"text": navigation.read_text().replace("\n", "\r\n"),
},
},
),
)
requests = [
("textDocument/definition", {"position": at(11, 3)}),
(
"textDocument/references",
{"position": at(4, 10), "context": {"includeDeclaration": True}},
),
("textDocument/documentHighlight", {"position": at(8, 9)}),
("textDocument/documentHighlight", {"position": at(9, 13)}),
("textDocument/definition", {"position": at(9, 28)}),
("textDocument/documentSymbol", {}),
("textDocument/foldingRange", {}),
("textDocument/selectionRange", {"positions": [at(9, 23)]}),
]
results = []
for offset, (method, params) in enumerate(requests):
send(proc, event(method, {"textDocument": doc, **params}, 10 + offset))
reply = receive_reply(proc, 10 + offset)
assert reply["id"] == 10 + offset and "result" in reply, reply
results.append(reply["result"])
location = lambda *args: {"uri": nav_uri, "range": span(*args)}
assert results[0] == [location(6, 7, 23)], results[0]
assert results[1] == [location(4, 8, 24), location(9, 31, 47)], results[1]
assert results[2] == [
{"range": span(8, 9, 10), "kind": 3},
{"range": span(9, 10, 11), "kind": 2},
], results[2]
assert results[3] == [
{"range": span(9, 13, 14), "kind": 2},
{"range": span(9, 18, 19), "kind": 2},
{"range": span(9, 21, 22), "kind": 1},
], results[3]
assert results[4] == [location(6, 30, 32)], results[4]
code = results[5][0]
assert code["name"] == "Code:", results[5]
assert [child["name"] for child in code["children"]] == [
"navigation-count",
"navigation-greet",
"navigation",
], code
assert {"startLine": 6, "endLine": 9} in results[6], results[6]
assert results[7][0]["range"] == span(9, 23, 27), results[7]
assert results[7][0]["parent"]["range"] == span(9, 4, 48), results[7]
send(proc, event("textDocument/didClose", {"textDocument": doc}))
FULL_CAPABILITIES = {
"workspace": {"diagnostics": {"refreshSupport": True}},
"general": {"positionEncodings": ["utf-8", "utf-16"]},
"textDocument": {
"diagnostic": {},
"codeAction": {
"codeActionLiteralSupport": {
"codeActionKind": {"valueSet": ["quickfix", "refactor.rewrite"]}
},
"dataSupport": True,
"resolveSupport": {"properties": ["edit"]},
},
"hover": {"contentFormat": ["markdown", "plaintext"]},
"completion": {
"completionItem": {
"documentationFormat": ["markdown", "plaintext"],
"resolveSupport": {
"properties": ["documentation", "detail", "additionalTextEdits"]
},
},
"completionList": {"itemDefaults": ["editRange"]},
},
"signatureHelp": {
"signatureInformation": {
"documentationFormat": ["markdown", "plaintext"],
"parameterInformation": {"labelOffsetSupport": True},
"activeParameterSupport": True,
}
},
"semanticTokens": {
"requests": {"range": True, "full": {"delta": True}},
"tokenTypes": ["function", "macro", "keyword", "variable", "parameter"],
"tokenModifiers": ["declaration", "definition"],
"formats": ["relative"],
},
"inlayHint": {"resolveSupport": {"properties": ["tooltip"]}},
},
}
def column(text, prefix, encoding):
head = text[:prefix]
if encoding == "utf-8":
return len(head.encode())
if encoding == "utf-16":
return len(head.encode("utf-16-le")) // 2
return len(head)
def intelligence(proc, encoding, full):
intel = Path("tests/fixtures/intel.el").resolve()
text = intel.read_text()
uri = intel.as_uri()
doc = {"uri": uri}
line6 = text.split("\n")[6]
col = lambda prefix: column(line6, prefix, encoding)
send(
proc,
event(
"textDocument/didOpen",
{
"textDocument": {
"uri": uri,
"languageId": "emacs-lisp",
"version": 1,
"text": text,
}
},
),
)
next_id = iter(range(100, 200))
def call(method, params):
request_id = next(next_id)
send(proc, event(method, params, request_id))
reply = receive_reply(proc, request_id)
assert reply["id"] == request_id and "result" in reply, reply
return reply["result"]
completion = call(
"textDocument/completion",
{"textDocument": doc, "position": at(6, col(len(" (navigation-g")))},
)
labels = [item["label"] for item in completion["items"]]
assert "navigation-greet" in labels, labels
item = next(i for i in completion["items"] if i["label"] == "navigation-greet")
edit_range = span(6, col(3), col(len(" (navigation-g")))
if full:
assert completion["itemDefaults"]["editRange"] == edit_range, completion
else:
assert item["textEdit"]["range"] == edit_range, item
resolved = call("completionItem/resolve", item)
assert resolved["detail"] == "(navigation-greet NAME 😀)", resolved
if full:
assert resolved["additionalTextEdits"] == [
{"range": span(4, 0, 0), "newText": "(require 'navigation)\n\n"}
], resolved
assert resolved["documentation"]["kind"] == "markdown", resolved
else:
assert "additionalTextEdits" not in resolved, resolved
hover = call("textDocument/hover", {"textDocument": doc, "position": at(6, col(5))})
assert hover["contents"]["kind"] == ("markdown" if full else "plaintext"), hover
assert "(navigation-greet NAME 😀)" in hover["contents"]["value"], hover
assert hover["range"] == span(6, col(3), col(19)), hover
definition = call(
"textDocument/definition", {"textDocument": doc, "position": at(6, col(5))}
)
assert definition[0]["uri"].endswith("tests/fixtures/navigation.el"), definition
signature = call(
"textDocument/signatureHelp",
{"textDocument": doc, "position": at(6, col(line6.index("(length")))},
)
assert signature["activeParameter"] == 1, signature
information = signature["signatures"][0]
assert information["label"] == "(navigation-greet NAME 😀)", signature
if full:
label = information["label"]
start = label.index("😀")
assert information["parameters"][1]["label"] == [
column(label, start, encoding),
column(label, start + 1, encoding),
], signature
else:
assert information["parameters"][1]["label"] == "😀", signature
hints = call(
"textDocument/inlayHint",
{"textDocument": doc, "range": {"start": at(0, 0), "end": at(11, 0)}},
)
greet = [
(hint["label"], hint["position"])
for hint in hints
if hint["data"]["function"] == "navigation-greet"
]
assert greet == [
("name:", at(6, col(line6.index('"')))),
("😀:", at(6, col(line6.index("(length")))),
], hints
resolved_hint = call("inlayHint/resolve", hints[0])
if full:
assert "(navigation-greet NAME 😀)" in resolved_hint["tooltip"], resolved_hint
else:
assert "tooltip" not in resolved_hint, resolved_hint
tokens = call("textDocument/semanticTokens/full", {"textDocument": doc})
assert tokens["data"] and len(tokens["data"]) % 5 == 0, tokens
send(
proc,
event(
"textDocument/didChange",
{
"textDocument": {"uri": uri, "version": 2},
"contentChanges": [edit(7, 3, 7, 9, "mapc")],
},
),
)
delta = call(
"textDocument/semanticTokens/full/delta",
{"textDocument": doc, "previousResultId": tokens["resultId"]},
)
assert "edits" in delta and delta["resultId"] != tokens["resultId"], delta
ranged = call(
"textDocument/semanticTokens/range",
{"textDocument": doc, "range": span(6, 0, col(len(line6)))},
)
assert ranged["data"] and len(ranged["data"]) < len(tokens["data"]), ranged
symbols = call("workspace/symbol", {"query": "navigation-gr"})
assert any(symbol["name"] == "navigation-greet" for symbol in symbols), symbols
send(proc, event("textDocument/didClose", {"textDocument": doc}))
def diagnostics(proc, encoding, pull):
uri = Path("tests/fixtures/diagnostic.el").resolve().as_uri()
document = {"uri": uri}
line = '(message "日本😀") )'
send(proc, event("textDocument/didOpen", {"textDocument": {
"uri": uri, "version": 1, "languageId": "emacs-lisp", "text": line,
}}))
def receive_push():
while True:
reply = receive(proc)
assert reply.get("method") == "textDocument/publishDiagnostics", reply
if reply["params"]["uri"] == uri:
return reply["params"]["diagnostics"]
def receive_pull(request_id, previous=None):
params = {"textDocument": document}
if previous is not None:
params["previousResultId"] = previous
send(proc, event("textDocument/diagnostic", params, request_id))
return receive_reply(proc, request_id)["result"]
if pull:
report = receive_pull(301)
assert report["kind"] == "full", report
previous = report["resultId"]
assert receive_pull(302, previous) == {"kind": "unchanged", "resultId": previous}
items = report["items"]
else:
items = receive_push()
syntax = next(item for item in items if item["code"] == "syntax")
assert syntax["range"] == span(
0, column(line, len(line) - 1, encoding), column(line, len(line), encoding)
), syntax
send(proc, event("textDocument/didChange", {
"textDocument": {"uri": uri, "version": 2},
"contentChanges": [{"text": line[:-1]}],
}))
if pull:
report = receive_pull(303, previous)
assert report["kind"] == "full" and report["items"] == [], report
else:
assert receive_push() == []
send(proc, event("textDocument/didClose", {"textDocument": document}))
def session(binary, record, capabilities, encoding, full):
with tempfile.TemporaryDirectory() as directory:
log = Path(directory, "server.log")
cmd = [
"lsp-touchstone",
"proxy",
"run-proxy",
"--record-file",
record,
"--server-command-args",
binary,
"server",
"run-server",
"--log-file",
str(log),
]
env = dict(
os.environ,
ELSMITH_CONFIG_DIR=directory,
XDG_CACHE_HOME=str(Path("test-out/cache").resolve()),
)
with subprocess.Popen(
cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, env=env
) as proc:
try:
fixture = Path("tests/fixtures/sample.el").resolve()
uri = fixture.as_uri()
root = fixture.parent.as_uri()
send(
proc,
event(
"initialize",
{
"processId": None,
"rootUri": root,
"capabilities": capabilities,
"initializationOptions": {"trustWorkspace": True},
},
1,
),
)
reply = receive(proc)
assert (
reply["id"] == 1
and reply["result"]["capabilities"]["positionEncoding"] == encoding
), reply
send(proc, event("initialized", {}))
wide = {5: 9, 7: 13, 9: 17}.get if encoding == "utf-8" else int
send(
proc,
event(
"textDocument/didOpen",
{
"textDocument": {
"uri": uri,
"languageId": "emacs-lisp",
"version": 1,
"text": fixture.read_text().replace("\n", "\r\n"),
},
},
),
)
send(
proc,
event(
"textDocument/didChange",
{
"textDocument": {"uri": uri, "version": 2},
"contentChanges": [
{"text": ';; 日本😀\r\n(message "old")\r\n'},
edit(0, wide(5), 0, wide(7), "😀😀"),
edit(0, wide(9), 1, 0, "\r\n;; extra\r\n"),
edit(2, 10, 2, 13, "new"),
edit(3, 0, 3, 0, ";; tail\r\n"),
],
},
),
)
send(
proc, event("textDocument/didSave", {"textDocument": {"uri": uri}})
)
send(
proc,
event(
"workspace/didChangeConfiguration",
{
"settings": {
"trustWorkspace": True,
"emacs_path": "./workspace-emacs",
},
},
),
)
send(
proc, event("textDocument/didClose", {"textDocument": {"uri": uri}})
)
if encoding == "utf-16":
navigate(proc, uri)
intelligence(proc, encoding, full)
diagnostics(proc, encoding, full)
send(proc, event("shutdown", request_id=2))
assert receive_reply(proc, 2) == {"jsonrpc": "2.0", "id": 2, "result": None}
send(proc, event("exit"))
assert proc.wait(timeout=10) == 0
finally:
if proc.poll() is None:
proc.kill()
lines = log.read_text().splitlines()
trust = [line for line in lines if line.startswith("Trust epoch")]
assert trust == ["Trust epoch 0, 0/1 file workspace roots trusted"] * 2, lines
assert any(line.startswith("Indexed ") for line in lines), lines
def main():
parser = argparse.ArgumentParser()
parser.add_argument("binary", nargs="?", default="target/debug/elsmith")
binary = str(Path(parser.parse_args().binary).resolve())
session(binary, "test-out/proxy.ndjson", {"textDocument": {"publishDiagnostics": {}}}, "utf-16", False)
session(binary, "test-out/proxy-full.ndjson", FULL_CAPABILITIES, "utf-8", True)
if __name__ == "__main__":
main()