elsmith 0.1.1

An Emacs Lisp language server with Lean-verified protocol and editing rules
Documentation
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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
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()