elsmith 0.1.0

An Emacs Lisp language server with Lean-verified protocol and editing rules
Documentation
import argparse
import gzip
import json
import os
import re
import shutil
import signal
import subprocess
import sys
import tempfile
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
OUTPUT = ROOT / "test-out/editors"
FIXTURE = """;;; sample.el --- Editor fixture -*- lexical-binding: t; -*-
(require 'seq)
(defun elsmith-editor-probe (input)
(let ((local input) (elsmith-editor-unused nil))
(list local
(seq-filter #'identity local))))
"""
FORMATTED = """;;; sample.el --- Editor fixture -*- lexical-binding: t; -*-
(require 'seq)
(defun elsmith-editor-probe (input)
  (let ((renamed input) (elsmith-editor-unused nil))
    (list renamed
          (seq-filter #'identity renamed))))
"""


def definition():
    library = subprocess.check_output([
        "emacs", "-Q", "--batch", "--eval",
        """(princ (expand-file-name "emacs-lisp/seq.el.gz"
                  (expand-file-name "../lisp" data-directory)))""",
    ], text=True)
    with gzip.open(library, "rt", encoding="utf-8") as source:
        return next(
            (line, text.index("seq-filter"), text.rstrip("\n"))
            for line, text in enumerate(source)
            if re.match(r"^\(cl-defgeneric seq-filter\b", text)
        )


def verify_record(record, editor):
    entries = [json.loads(line) for line in record.read_text().splitlines()]
    received = {
        entry.get("Method") for entry in entries
        if entry.get("Direction") == "server-to-client" and entry.get("Kind") == "response"
    }
    required = {
        "initialize", "textDocument/completion", "completionItem/resolve",
        "textDocument/hover", "textDocument/definition", "textDocument/prepareRename",
        "textDocument/rename", "textDocument/formatting", "shutdown",
    }
    assert required <= received, required - received
    for method in ("textDocument/didOpen", "textDocument/didChange", "exit"):
        assert any(entry.get("Method") == method for entry in entries), (record, method)
    assert entries[-1].get("SessionEnd", {}).get("ExitCode") == 0, entries[-1]
    with record.with_suffix(".protocol.json").open("w") as output:
        subprocess.run([
            "lsp-touchstone", "check", "check-record", "--target", "both",
            "--record-file", str(record),
        ], stdout=output, check=True, timeout=30)
    report_path = record.with_suffix(".protocol.json")
    if editor == "vowls":
        subprocess.run([
            sys.executable, str(ROOT / "tests/protocol_report.py"), str(report_path),
        ], check=True)
    report = json.loads(report_path.read_text())
    assert report["Errors"] == 0, report["Findings"]
    assert all(finding["Party"] == "client" for finding in report["Findings"]), report["Findings"]
    return {"errors": report["Errors"], "warnings": report["Warnings"]}


def run(editor, project, expected_definition, binary):
    project.mkdir()
    subprocess.run(["git", "init", "-q", str(project)], check=True)
    source = project / "sample.el"
    source.write_text(FIXTURE)
    common_lisp = project / "sample.lisp"
    common_lisp.write_text("(defun common-lisp-example () nil)\n")
    line, column, text = expected_definition
    base = OUTPUT / editor
    record = base.with_suffix(".ndjson")
    record.unlink(missing_ok=True)
    result = base.with_suffix(".json")
    result.unlink(missing_ok=True)
    config = {
        "editor": editor, "file": str(source), "commonLisp": str(common_lisp),
        "definitionLine": line, "definitionColumn": column, "definitionText": text,
        "expected": FORMATTED, "result": str(result),
        "command": [
            "lsp-touchstone", "proxy", "run-proxy", "--record-file", str(record),
            "--server-command-args", str(binary), "server", "run-server",
            "--log-file", str(base.with_suffix(".server.log")),
        ],
    }
    if editor == "vowls":
        for library in Path(os.environ["ELSMITH_TEST_VOWLS"]).glob("*.el"):
            shutil.copyfile(library, project / library.name)
        config["dogfood"] = str(project / "vowls.el")
    config_path = project / "editor.json"
    config_path.write_text(json.dumps(config))
    env = dict(
        os.environ,
        ELSMITH_EDITOR_CONFIG=str(config_path),
        ELSMITH_CONFIG_DIR=str(project / "config"),
        XDG_CACHE_HOME=str(OUTPUT / "cache"),
    )
    if editor == "neovim":
        cmd = ["nvim", "--headless", "-u", "NONE", "-l", str(ROOT / "tests/editors/neovim.lua")]
    else:
        cmd = ["emacs", "--batch", "-Q"]
        if editor == "vowls":
            cmd += ["-L", os.environ["ELSMITH_TEST_VOW"], "-L", os.environ["ELSMITH_TEST_VOWLS"]]
        cmd += ["-l", str(ROOT / "tests/editors/emacs.el")]
    log = base.with_suffix(".editor.log")
    with log.open("w") as output:
        proc = subprocess.Popen(cmd, env=env, cwd=project, stdout=output,
                                stderr=subprocess.STDOUT, start_new_session=True)
        try:
            assert proc.wait(timeout=75) == 0, f"{editor} failed, see {log}"
        finally:
            if proc.poll() is None:
                os.killpg(proc.pid, signal.SIGKILL)
                proc.wait(timeout=10)
    data = json.loads(result.read_text())
    data["protocol"] = verify_record(record, editor)
    return data


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--binary", type=Path, default=ROOT / "target/debug/elsmith")
    parser.add_argument("editors", nargs="*", choices=("vowls", "eglot", "neovim"))
    args = parser.parse_args()
    OUTPUT.mkdir(parents=True, exist_ok=True)
    expected = definition()
    names = args.editors or ("vowls", "eglot", "neovim")
    with tempfile.TemporaryDirectory(prefix="elsmith-editors-") as directory:
        summary = {name: run(name, Path(directory) / name, expected, args.binary.resolve())
                   for name in names}
    (OUTPUT / "summary.json").write_text(json.dumps(summary, indent=2) + "\n")
    print(json.dumps(summary, indent=2))


if __name__ == "__main__":
    main()