elsmith 0.1.0

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

ANALYZE = r"""
(let ((file (car command-line-args-left))
      (reports nil)
      (heads nil))
  (setq command-line-args-left nil)
  (with-temp-buffer
    (insert-file-contents file)
    (setq buffer-file-name file)
    (emacs-lisp-mode)
    (hack-local-variables)
    (eval-buffer nil nil file nil t)
    (goto-char (point-min))
    (condition-case nil
        (while t
          (elisp-scope-analyze-form
           (lambda (role pos sym _id def)
             (push (list pos (symbol-name role) (symbol-name (bare-symbol sym)) def) reports))))
      (end-of-file nil))
    (goto-char (point-min))
    (while (re-search-forward "(\\(\\(?:\\sw\\|\\s_\\)+\\)" nil t)
      (let ((sym (intern-soft (match-string 1))))
        (when (and sym (fboundp sym))
          (push (cons (symbol-name sym)
                      (cond ((special-form-p sym) "special-form")
                            ((macrop sym) "macro")
                            (t "function")))
                heads)))))
  (princ (json-encode (list (cons 'reports (vconcat (mapcar #'vconcat (nreverse reports))))
                            (cons 'heads heads)))))
"""

PRELUDE = "(require 'json)"


def analyze(path):
    result = subprocess.run(
        ["emacs", "-Q", "--batch", "--eval", PRELUDE, "--eval", ANALYZE, str(path)],
        capture_output=True,
        text=True,
        check=True,
    )
    return json.loads(result.stdout)


def main():
    directory = Path(sys.argv[1])
    expected = {"heads": {}, "files": {}}
    for path in sorted(directory.glob("*.el")):
        data = analyze(path.resolve())
        expected["files"][path.name] = [
            {"pos": pos, "role": role, "name": name, "def": def_}
            for pos, role, name, def_ in data["reports"]
        ]
        expected["heads"].update(dict(data["heads"]))
    expected["heads"] = dict(sorted(expected["heads"].items()))
    Path(directory, "expected.json").write_text(
        json.dumps(expected, indent=2, ensure_ascii=False) + "\n"
    )


if __name__ == "__main__":
    main()