elsmith 0.1.1

An Emacs Lisp language server with Lean-verified protocol and editing rules
Documentation
use std::io::Write;
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use std::process::{Command, Output, Stdio};
use std::{env, fs};

use serde_json::{Value, json};

fn binary() -> Command {
    Command::new(env!("CARGO_BIN_EXE_elsmith"))
}

fn send(input: &mut impl Write, bytes: &[u8]) {
    write!(input, "Content-Length: {}\r\n\r\n", bytes.len()).unwrap();
    input.write_all(bytes).unwrap();
}

fn session(workdir: &Path, messages: &[Value], invalid_json: bool) -> Output {
    let mut child = binary()
        .args(["server", "run-server", "--debug"])
        .current_dir(workdir)
        .env("PATH", "")
        .env("ELSMITH_CONFIG_DIR", workdir.join("user-config"))
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .unwrap();
    {
        let mut input = child.stdin.take().unwrap();
        if invalid_json {
            send(&mut input, b"{");
        }
        for message in messages {
            send(&mut input, &serde_json::to_vec(message).unwrap());
        }
    }
    child.wait_with_output().unwrap()
}

fn responses(mut bytes: &[u8]) -> Vec<Value> {
    let mut messages = Vec::new();
    while !bytes.is_empty() {
        let separator = bytes.windows(4).position(|w| w == b"\r\n\r\n").unwrap();
        let header = str::from_utf8(&bytes[..separator]).unwrap();
        let length = header
            .strip_prefix("Content-Length: ")
            .unwrap()
            .parse()
            .unwrap();
        let (body, rest) = bytes[separator + 4..].split_at(length);
        messages.push(serde_json::from_slice(body).unwrap());
        bytes = rest;
    }
    messages
}

#[test]
fn works_without_emacs_and_workspace_settings_cannot_execute_a_process() {
    let temp = tempfile::tempdir().unwrap();
    let dir = temp.path();
    let script = dir.join("workspace-emacs");
    let marker = dir.join("spawned");
    let path = env::var_os("PATH").unwrap_or_default();
    let shell = std::iter::once(PathBuf::from("/bin/sh"))
        .chain(env::split_paths(&path).map(|dir| dir.join("sh")))
        .find(|path| path.is_absolute() && path.is_file())
        .expect("the test needs a POSIX shell for its executable");
    fs::write(
        &script,
        format!(
            "#!{}\nprintf spawned > \"${{0%/*}}/spawned\"\n",
            shell.display()
        ),
    )
    .unwrap();
    fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap();
    assert!(
        Command::new(shell)
            .arg(&script)
            .current_dir(dir)
            .status()
            .unwrap()
            .success()
    );
    assert_eq!(fs::read_to_string(&marker).unwrap(), "spawned");
    fs::remove_file(&marker).unwrap();
    fs::write(
        dir.join("elsmith.toml"),
        "trustWorkspace = true\nemacs_path = \"./workspace-emacs\"\n",
    )
    .unwrap();
    let settings = json!({"trustWorkspace": true, "emacs_path": script});
    let uri = url::Url::from_directory_path(dir).unwrap();
    let fake_uri = uri.join("sample.el").unwrap();
    let output = session(
        dir,
        &[
            json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{"rootUri":uri.as_str(),"capabilities":{},"initializationOptions":settings}}),
            json!({"jsonrpc":"2.0","method":"initialized","params":{}}),
            json!({"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{"settings":settings}}),
            json!({"jsonrpc":"2.0","method":"textDocument/didOpen","params":{"textDocument":{"uri":fake_uri.as_str(),"languageId":"emacs-lisp","version":0,"text":"(message \"日本😀\")\r\n"}}}),
            json!({"jsonrpc":"2.0","method":"textDocument/didSave","params":{"textDocument":{"uri":fake_uri.as_str()}}}),
            json!({"jsonrpc":"2.0","id":2,"method":"workspace/executeCommand","params":{"command":"elsmith.trustWorkspace","arguments":[settings]}}),
            json!({"jsonrpc":"2.0","id":3,"method":"shutdown"}),
            json!({"jsonrpc":"2.0","method":"exit"}),
        ],
        false,
    );
    assert!(output.status.success());
    assert!(!marker.exists());
    assert!(!dir.join("user-config/trusted-roots.toml").exists());
    let log = str::from_utf8(&output.stderr).unwrap();
    assert_eq!(
        log.matches("Trust epoch 0, 0/1 file workspace roots trusted")
            .count(),
        2
    );
    let messages = responses(&output.stdout);
    assert_eq!(messages.len(), 3);
    assert_eq!(
        messages[0]["result"]["capabilities"]["positionEncoding"],
        "utf-16"
    );
    assert_eq!(messages[1]["error"]["code"], -32601);
    assert!(messages[2]["result"].is_null());
}

#[test]
fn lifecycle_and_rpc_errors_have_the_expected_codes() {
    let temp = tempfile::tempdir().unwrap();
    for exit in [
        json!({"jsonrpc":"2.0","method":"exit"}),
        json!({"jsonrpc":"2.0","method":"exit","params":{}}),
        json!({"jsonrpc":"2.0","method":"exit","params":null}),
    ] {
        let output = session(temp.path(), std::slice::from_ref(&exit), false);
        assert_eq!(output.status.code(), Some(1));
        assert!(output.stdout.is_empty());
        let output = session(
            temp.path(),
            &[
                json!({"jsonrpc":"2.0","id":0,"method":"shutdown"}),
                json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{"capabilities":{"general":{"positionEncodings":["utf-32","utf-8"]}}}}),
                json!({"jsonrpc":"2.0","method":"initialized","params":{}}),
                json!({"jsonrpc":"2.0","id":"a","method":"unknown"}),
                json!({"jsonrpc":"2.0","method":"$/cancelRequest","params":{"id":"a"}}),
                json!({"jsonrpc":"2.0","id":2,"method":"shutdown"}),
                json!({"jsonrpc":"2.0","id":3,"method":"initialize","params":{"capabilities":{}}}),
                exit,
            ],
            true,
        );
        assert!(output.status.success());
        let responses = responses(&output.stdout);
        assert_eq!(responses.len(), 6);
        assert_eq!(responses[0]["error"]["code"], -32700);
        assert_eq!(responses[0]["id"], Value::Null);
        assert_eq!(responses[1]["error"]["code"], -32002);
        assert_eq!(
            responses[2]["result"]["capabilities"]["positionEncoding"],
            "utf-32"
        );
        assert_eq!(responses[3]["error"]["code"], -32601);
        assert_eq!(responses[3]["id"], "a");
        assert!(responses[4]["result"].is_null());
        assert_eq!(responses[5]["error"]["code"], -32600);
    }
}

#[test]
fn file_check_and_trust_use_pascal_case_and_cli_exit_codes() {
    let temp = tempfile::tempdir().unwrap();
    let dir = temp.path();
    let run = |args: &[&str]| {
        binary()
            .args(args)
            .current_dir(dir)
            .env("XDG_CONFIG_HOME", dir.join("config"))
            .env_remove("ELSMITH_CONFIG_DIR")
            .output()
            .unwrap()
    };
    let text = "#!/bin/sh\r\n;; -*- lexical-binding: t; -*-\r\n\"日本😀\"\r\n";
    fs::write(dir.join("sample.el"), text).unwrap();
    let output = run(&["check", "check-file", "--file", "sample.el"]);
    assert!(output.status.success());
    assert_eq!(
        serde_json::from_slice::<Value>(&output.stdout).unwrap(),
        json!({"File":"sample.el","LexicalBinding":true,"Lines":3,"Bytes":text.len(),"Diagnostics":[]})
    );
    assert!(run(&["check", "check-file", "help"]).status.success());
    fs::write(dir.join("help"), text).unwrap();
    let file_named_help = run(&["check", "check-file", "--file", "help"]);
    assert!(file_named_help.status.success());
    assert_eq!(
        serde_json::from_slice::<Value>(&file_named_help.stdout).unwrap()["File"],
        "help"
    );
    let version = format!(" {}\n", env!("CARGO_PKG_VERSION"));
    assert_eq!(
        run(&["--version"]).stdout,
        format!("elsmith{version}").as_bytes()
    );
    let nested_version = run(&["server", "run-server", "--version"]);
    assert!(nested_version.status.success());
    assert!(nested_version.stdout.ends_with(version.as_bytes()));
    assert_eq!(run(&["check", "check-file"]).status.code(), Some(252));
    assert_eq!(
        run(&["check", "check-file", "--file", "missing"])
            .status
            .code(),
        Some(254)
    );
    assert_eq!(
        run(&["server", "run-server", "--log-file", "missing/log"])
            .status
            .code(),
        Some(255)
    );
    let add = run(&["trust", "add-root", "--path", "."]);
    assert!(add.status.success(), "{:?}", add);
    assert!(dir.join("config/elsmith/trusted-roots.toml").exists());
    assert_eq!(
        serde_json::from_slice::<Value>(&add.stdout).unwrap(),
        json!({"Roots":[dir.canonicalize().unwrap()]})
    );
    assert_eq!(run(&["trust", "list-roots"]).stdout, add.stdout);
    let remove = run(&["trust", "remove-root", "--path", "."]);
    assert!(remove.status.success());
    assert_eq!(
        serde_json::from_slice::<Value>(&remove.stdout).unwrap(),
        json!({"Roots":[]})
    );
}

#[test]
fn navigates_within_a_file_over_stdio() {
    let temp = tempfile::tempdir().unwrap();
    let uri = "file:///tmp/nav.el";
    let text = ";;; nav.el --- Navigation -*- lexical-binding: t -*-\r\n;;; Code:\r\n(defun nav-emoji (😀 x) \"Doc 日本.\" (list 😀 x))\r\n(nav-emoji 1 2)\r\n";
    let at = |line: u32, character: u32| json!({"line": line, "character": character});
    let doc = json!({"uri": uri});
    let request = |id: u32, method: &str, params: Value| json!({"jsonrpc":"2.0","id":id,"method":method,"params":params});
    let output = session(
        temp.path(),
        &[
            request(1, "initialize", json!({"capabilities":{}})),
            json!({"jsonrpc":"2.0","method":"initialized","params":{}}),
            json!({"jsonrpc":"2.0","method":"textDocument/didOpen","params":{"textDocument":{"uri":uri,"languageId":"emacs-lisp","version":1,"text":text}}}),
            request(
                2,
                "textDocument/definition",
                json!({"textDocument":doc,"position":at(3, 4)}),
            ),
            request(
                3,
                "textDocument/references",
                json!({"textDocument":doc,"position":at(2, 18),"context":{"includeDeclaration":true}}),
            ),
            request(
                4,
                "textDocument/documentHighlight",
                json!({"textDocument":doc,"position":at(2, 40)}),
            ),
            request(
                5,
                "textDocument/documentSymbol",
                json!({"textDocument":doc}),
            ),
            request(6, "textDocument/foldingRange", json!({"textDocument":doc})),
            request(
                7,
                "textDocument/selectionRange",
                json!({"textDocument":doc,"positions":[at(2, 43)]}),
            ),
            request(
                8,
                "textDocument/declaration",
                json!({"textDocument":doc,"position":at(3, 4)}),
            ),
            request(9, "shutdown", Value::Null),
            json!({"jsonrpc":"2.0","method":"exit"}),
        ],
        false,
    );
    let messages = responses(&output.stdout);
    let capabilities = &messages[0]["result"]["capabilities"];
    for provider in [
        "documentSymbolProvider",
        "definitionProvider",
        "declarationProvider",
        "referencesProvider",
        "documentHighlightProvider",
        "foldingRangeProvider",
        "selectionRangeProvider",
    ] {
        assert_eq!(capabilities[provider], true, "{provider}");
    }
    let range =
        |line: u32, start: u32, end: u32| json!({"start": at(line, start), "end": at(line, end)});
    assert_eq!(
        messages[1]["result"],
        json!([{"uri": uri, "range": range(2, 7, 16)}])
    );
    assert_eq!(
        messages[2]["result"],
        json!([{"uri": uri, "range": range(2, 18, 20)}, {"uri": uri, "range": range(2, 40, 42)}])
    );
    assert_eq!(
        messages[3]["result"],
        json!([{"range": range(2, 18, 20), "kind": 3}, {"range": range(2, 40, 42), "kind": 2}])
    );
    assert_eq!(messages[4]["result"][0]["name"], "Code:");
    assert_eq!(messages[4]["result"][0]["children"][0]["name"], "nav-emoji");
    assert_eq!(
        messages[4]["result"][0]["children"][0]["selectionRange"],
        range(2, 7, 16)
    );
    assert!(
        messages[5]["result"]
            .as_array()
            .unwrap()
            .iter()
            .any(|fold| fold["kind"] == "region")
    );
    assert_eq!(messages[6]["result"][0]["range"], range(2, 43, 44));
    assert_eq!(
        messages[6]["result"][0]["parent"]["range"],
        range(2, 34, 45)
    );
    assert_eq!(messages[7]["result"], messages[1]["result"]);
    assert_eq!(messages[8]["result"], Value::Null);
}