elsmith 0.1.1

An Emacs Lisp language server with Lean-verified protocol and editing rules
Documentation
import os
import subprocess
import tempfile
from pathlib import Path

from protocol_proxy import at, event, receive_reply, send

HEADER = ";;; -*- lexical-binding: t -*-\n"
OPTIONS = {"tabSize": 8, "insertSpaces": True}


def position(text, start):
    prefix = text[:start]
    return at(prefix.count("\n"), len(prefix.rsplit("\n", 1)[-1].encode("utf-16-le")) // 2)


def apply(text, edits):
    def offset(point):
        pieces = text.splitlines(keepends=True) + [""]
        line = point["line"]
        prefix = pieces[line].encode("utf-16-le")[: 2 * point["character"]]
        return sum(map(len, pieces[:line])) + len(prefix.decode("utf-16-le"))

    spans = sorted(
        (offset(edit["range"]["start"]), offset(edit["range"]["end"]), edit["newText"])
        for edit in edits
    )
    for start, end, replacement in reversed(spans):
        text = text[:start] + replacement + text[end:]
    return text


class Session:
    def __init__(self, directory):
        self.id = 0
        self.process = subprocess.Popen(
            ["target/debug/elsmith", "server", "run-server"],
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            env=dict(os.environ, ELSMITH_CONFIG_DIR=str(directory / "config")),
        )
        result = self.call(
            "initialize",
            {
                "processId": None,
                "rootUri": directory.as_uri(),
                "capabilities": {
                    "textDocument": {"rename": {"prepareSupport": True}},
                    "workspace": {"workspaceEdit": {"documentChanges": True}},
                },
            },
        )
        assert result["capabilities"]["renameProvider"] == {"prepareProvider": True}
        self.notify("initialized", {})

    def notify(self, method, params=None):
        send(self.process, event(method, params))

    def call(self, method, params=None, error=None):
        self.id += 1
        send(self.process, event(method, params, self.id))
        reply = receive_reply(self.process, self.id)
        if error is not None:
            assert reply["error"]["code"] == error, reply
            return None
        assert "result" in reply, (method, reply)
        return reply["result"]

    def open(self, path, text):
        doc = {"uri": path.as_uri()}
        self.notify("textDocument/didOpen", {
            "textDocument": dict(doc, version=1, languageId="emacs-lisp", text=text)
        })
        return doc

    def change(self, doc, version, text):
        self.notify("textDocument/didChange", {
            "textDocument": dict(doc, version=version),
            "contentChanges": [{"text": text}],
        })

    def close(self, doc):
        self.notify("textDocument/didClose", {"textDocument": doc})

    def stop(self):
        assert self.call("shutdown") is None
        self.notify("exit")
        assert self.process.wait(timeout=10) == 0


def rename_and_calls(session, directory, caller_path):
    local = HEADER + '(let ((f "😀")) (list f (f) #\'f \'f))\n'
    document = session.open(directory / "local.el", local)
    params = {"textDocument": document, "position": position(local, local.index("f (f)"))}
    assert session.call("textDocument/prepareRename", params)["placeholder"] == "f"
    edit = session.call("textDocument/rename", dict(params, newName="item"))
    change, = edit["documentChanges"]
    assert change["textDocument"] == dict(document, version=1)
    assert apply(local, change["edits"]) == local.replace("((f ", "((item ").replace("list f ", "list item ")
    for name in ("nil", ".", "123", "f foo", "t", ":keyword"):
        session.call("textDocument/rename", dict(params, newName=name), error=-32803)

    def unsafe(text, identifier, name=None, path=None):
        session.close(document)
        doc = session.open(path or directory / "local.el", text)
        query = {"textDocument": doc, "position": position(text, text.index(identifier))}
        if name:
            session.call("textDocument/rename", dict(query, newName=name), error=-32803)
        else:
            assert session.call("textDocument/prepareRename", query) is None, text
        session.close(doc)

    for body, identifier in [
        ("(let ((dyn 1)) dyn)", "dyn"),
        (HEADER + "(let ((f 1)) (elsmith-opaque f))", "f 1"),
        (HEADER + "(cl-defun local-probe (&key input) input)", "input"),
        (HEADER + "(cl-defstruct (example (:constructor example-build)) x) (example-build)", "example-build"),
        (HEADER + "(defvar later) (let ((later 1)) later)", "later 1"),
    ]:
        unsafe(body, identifier)
    unsafe(HEADER + "(let ((f 1)) (let ((g 2)) (list f g)))", "f 1", "g")
    raw = directory / "raw.el"
    raw.write_bytes(b";\xff\n")
    unsafe(HEADER + "(let ((f 1)) f)", "f 1", path=raw)
    raw.unlink()
    unsafe(";;; -*- coding: big5; lexical-binding: t -*-\n(let ((f 1)) f)", "f 1")

    source = HEADER + "(defun elsmith-target () nil)\n"
    doc = session.open(directory / "target.el", source)
    query = {"textDocument": doc, "position": position(source, source.index("elsmith-target"))}
    assert session.call("textDocument/prepareRename", query)["placeholder"] == "elsmith-target"
    change = session.call("textDocument/rename", dict(query, newName="elsmith-updated"))
    assert len(change["documentChanges"]) == 2, change
    edits = {item["textDocument"]["uri"]: item for item in change["documentChanges"]}
    caller = caller_path.read_text()
    updated = edits[caller_path.as_uri()]
    assert updated["textDocument"]["version"] is None
    assert len(updated["edits"]) == 5, updated
    modified = apply(caller, updated["edits"])
    assert "(elsmith-updated)" in modified and "'elsmith-target" in modified
    assert "(let ((elsmith-target fn))" in modified
    item, = session.call("textDocument/prepareCallHierarchy", query)
    incoming, = session.call("callHierarchy/incomingCalls", {"item": item})
    assert incoming["from"]["name"] == "elsmith-caller"
    assert len(incoming["fromRanges"]) == 3, incoming
    outgoing, = session.call("callHierarchy/outgoingCalls", {"item": incoming["from"]})
    assert outgoing["to"] == item and len(outgoing["fromRanges"]) == 3, outgoing
    session.call("textDocument/rename", dict(query, newName="elsmith-caller"), error=-32803)

    shadow = caller + "(cl-flet ((replacement () nil)) (elsmith-target))\n"
    session.open(caller_path, shadow)
    session.call("textDocument/rename", dict(query, newName="replacement"), error=-32803)
    session.close({"uri": caller_path.as_uri()})

    local_fn = HEADER + "(defun wraps () (cl-labels ((a () (b)) (b () (a))) (a)))\n"
    fn_doc = session.open(directory / "functions.el", local_fn)
    at_b = {"textDocument": fn_doc, "position": position(local_fn, local_fn.index("(b)") + 1)}
    fn_item, = session.call("textDocument/prepareCallHierarchy", at_b)
    callers, = session.call("callHierarchy/incomingCalls", {"item": fn_item})
    assert callers["from"]["name"] == "a", callers


def emacs_indent(text):
    return subprocess.run(
        [
            "emacs", "-Q", "--batch", "--eval",
            """(with-temp-buffer
                 (let ((coding-system-for-read 'utf-8-unix))
                   (insert-file-contents "/dev/stdin"))
                 (emacs-lisp-mode)
                 (setq-local indent-tabs-mode nil)
                 (setq-local lisp-indent-local-overrides '((elsmith-with . 1)))
                 (indent-region (point-min) (point-max))
                 (princ (buffer-string)))""",
        ],
        input=text,
        text=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.DEVNULL,
        check=True,
    ).stdout


def formatting(session, directory):
    supported = HEADER + '''(defmacro elsmith-with (resource &rest body)
(declare (indent 1))
`(let ((it ,resource))
,@body))
(defun demo (x)
"First line.
    Keep this string."
;; Keep this comment.
(let ((a x)
(b (list x
x)))
(if a
(elsmith-with b
(message "b"))
(list a
b))))
(list
1
2)
(progn "😀" (list a
b))
'''
    document = session.open(directory / "format.el", supported)
    params = {"textDocument": document, "options": OPTIONS}
    edits = session.call("textDocument/formatting", params)
    actual = apply(supported, edits)
    expected = emacs_indent(supported)
    if actual != expected:
        import difflib
        raise AssertionError("".join(difflib.unified_diff(expected.splitlines(True), actual.splitlines(True))))
    assert "    Keep this string." in actual and ";; Keep this comment." in actual
    session.change(document, 2, actual)
    assert session.call("textDocument/formatting", params) == []

    dynamic = '''(defmacro dynamic (&rest body)
  (declare (indent indent-dynamically))
  (cons 'progn body))
   (dynamic (list
 x
       y))
(defun broken ()
 (list
 "open
  string bytes
'''
    session.change(document, 3, dynamic)
    assert session.call("textDocument/formatting", params) == []

    lines = "(progn\n(foo)\n(bar))\n"
    session.change(document, 4, lines)
    one = session.call("textDocument/rangeFormatting", dict(params, range={
        "start": at(1, 0), "end": at(2, 0),
    }))
    assert apply(lines, one) == "(progn\n  (foo)\n(bar))\n"
    session.change(document, 5, "(let ((a 1))\r\n")
    assert session.call("textDocument/onTypeFormatting", dict(params, position=at(1, 0), ch="\n")) == [
        {"range": {"start": at(1, 0), "end": at(1, 0)}, "newText": "  "},
    ]
    session.change(document, 6, "(progn\n(list))\n")
    assert session.call("textDocument/onTypeFormatting", dict(params, position=at(1, 7), ch=")")) == [
        {"range": {"start": at(1, 0), "end": at(1, 0)}, "newText": "  "},
    ]


def main():
    with tempfile.TemporaryDirectory() as temporary:
        root = Path(temporary)
        caller = root / "caller.el"
        caller.write_text(HEADER + """
(defun elsmith-caller (fn)
  (let ((elsmith-target fn))
    (list elsmith-target 'elsmith-target #'elsmith-target
          (elsmith-target) (funcall #'elsmith-target) (funcall fn)
          (apply (function elsmith-target) nil)
          (fboundp 'elsmith-target))))
""")
        session = Session(root)
        try:
            rename_and_calls(session, root, caller)
            formatting(session, root)
            session.stop()
        finally:
            if session.process.poll() is None:
                session.process.kill()
                session.process.wait()
    print("Rename, call hierarchy, and Emacs indentation oracle passed.")


if __name__ == "__main__":
    main()