use std::env;
use std::fs;
use std::io::{BufRead, BufReader, Read, Write};
use std::path::{Path, PathBuf};
use std::process::{Child, ChildStdin, Command, Stdio};
use std::sync::mpsc::{self, Receiver};
use std::time::{Duration, Instant};
use elsmith::trust::Allowlist;
use serde_json::{Value, json};
const HEADER: &str = ";;; -*- lexical-binding: t; -*-\n";
const WAIT: Duration = Duration::from_secs(12);
struct Session {
dir: tempfile::TempDir,
child: Child,
input: ChildStdin,
output: Receiver<Value>,
messages: Vec<Value>,
id: u64,
}
fn uri(file: &Path) -> String {
url::Url::from_file_path(file).unwrap().to_string()
}
fn emacs() -> Option<PathBuf> {
let path = env::var_os("PATH")?;
env::split_paths(&path)
.map(|dir| dir.join("emacs"))
.find(|path| path.is_absolute() && path.is_file())
}
impl Session {
fn start(capabilities: Value, trusted: bool, emacs: Option<&Path>) -> Self {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("workspace");
fs::create_dir(&root).unwrap();
let config = dir.path().join("config");
if trusted {
Allowlist::add(&config, &root).unwrap();
}
let mut command = Command::new(env!("CARGO_BIN_EXE_elsmith"));
command.args(["server", "run-server", "--debug"]);
if let Some(emacs) = emacs {
command.arg("--emacs").arg(emacs);
} else {
command.env("PATH", "");
}
let mut child = command
.env("ELSMITH_CONFIG_DIR", &config)
.env("XDG_CACHE_HOME", dir.path().join("cache"))
.env_remove("EMACSLOADPATH")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.spawn()
.unwrap();
let input = child.stdin.take().unwrap();
let mut reader = BufReader::new(child.stdout.take().unwrap());
let (sender, output) = mpsc::channel();
std::thread::spawn(move || {
let mut line = String::new();
while reader.read_line(&mut line).is_ok_and(|n| n != 0) {
let length = line
.trim()
.strip_prefix("Content-Length: ")
.unwrap()
.parse()
.unwrap();
line.clear();
reader.read_line(&mut line).unwrap();
assert_eq!(line, "\r\n");
line.clear();
let mut data = vec![0; length];
reader.read_exact(&mut data).unwrap();
if sender.send(serde_json::from_slice(&data).unwrap()).is_err() {
break;
}
}
});
let mut session = Self {
dir,
child,
input,
output,
messages: Vec::new(),
id: 0,
};
let result = session.call(
"initialize",
json!({
"rootUri": uri(&root),
"capabilities": capabilities,
}),
);
assert!(result.get("result").is_some(), "{result}");
session.notify("initialized", json!({}));
session
}
fn file(&self, name: &str) -> PathBuf {
self.dir.path().join("workspace").join(name)
}
fn send(&mut self, message: Value) {
let message = serde_json::to_vec(&message).unwrap();
write!(self.input, "Content-Length: {}\r\n\r\n", message.len()).unwrap();
self.input.write_all(&message).unwrap();
}
fn notify(&mut self, method: &str, params: Value) {
self.send(json!({"jsonrpc": "2.0", "method": method, "params": params}));
}
fn request(&mut self, method: &str, params: Value) -> u64 {
self.id += 1;
let id = self.id;
self.send(json!({"jsonrpc": "2.0", "method": method, "id": id, "params": params}));
id
}
fn call(&mut self, method: &str, params: Value) -> Value {
let id = self.request(method, params);
self.wait(|message| message["id"] == id)
}
fn wait(&mut self, predicate: impl Fn(&Value) -> bool) -> Value {
let deadline = Instant::now() + WAIT;
loop {
let message = self
.output
.recv_timeout(deadline.saturating_duration_since(Instant::now()))
.unwrap_or_else(|err| panic!("{err}: {:#?}", self.messages));
let matched = predicate(&message);
self.messages.push(message.clone());
if matched {
return message;
}
}
}
fn drain(&mut self, duration: Duration) {
let deadline = Instant::now() + duration;
while let Ok(message) = self
.output
.recv_timeout(deadline.saturating_duration_since(Instant::now()))
{
self.messages.push(message);
}
}
fn open(&mut self, file: &Path, version: i32, text: &str) {
self.notify("textDocument/didOpen", json!({
"textDocument": {"uri": uri(file), "languageId": "emacs-lisp", "version": version, "text": text}
}));
}
fn change(&mut self, file: &Path, version: i32, text: &str) {
self.notify("textDocument/didChange", json!({
"textDocument": {"uri": uri(file), "version": version}, "contentChanges": [{"text": text}]
}));
}
fn document_notification(&mut self, method: &str, file: &Path) {
self.notify(method, json!({"textDocument": {"uri": uri(file)}}));
}
fn pull(&mut self, file: &Path, previous: Option<&Value>) -> Value {
let mut params = json!({"textDocument": {"uri": uri(file)}});
if let Some(previous) = previous {
params["previousResultId"] = previous.clone();
}
self.call("textDocument/diagnostic", params)["result"].clone()
}
fn revoke(&mut self) {
let config = self.dir.path().join("config");
Allowlist::remove(&config, &self.dir.path().join("workspace")).unwrap();
self.notify("workspace/didChangeConfiguration", json!({"settings": {}}));
}
}
impl Drop for Session {
fn drop(&mut self) {
if self.child.try_wait().unwrap().is_none() {
let _ = self.child.kill();
let _ = self.child.wait();
}
}
}
fn items(report: &Value) -> &[Value] {
report.as_array().unwrap()
}
fn code<'a>(items: &'a [Value], code: &str) -> &'a Value {
items
.iter()
.find(|item| item["code"] == code)
.unwrap_or_else(|| panic!("{code}: {items:?}"))
}
fn published(message: &Value) -> bool {
message["method"] == "textDocument/publishDiagnostics"
}
fn progress_create(message: &Value) -> bool {
message["method"] == "window/workDoneProgress/create"
}
#[test]
fn push_ranges_count_emoji_and_clear_after_an_edit() {
let mut wire = Session::start(
json!({"textDocument": {"publishDiagnostics": {"versionSupport": true}}}),
false,
None,
);
let file = wire.file("sample.el");
wire.open(&file, 0, "(message \"日本😀\") )\n");
let push = wire.wait(published);
let params = &push["params"];
assert_eq!(params["version"], 0);
assert_eq!(
code(items(¶ms["diagnostics"]), "syntax")["range"],
json!({
"start": {"line": 0, "character": 17},
"end": {"line": 0, "character": 18},
})
);
wire.change(&file, 1, "(message \"日本😀\")\n");
assert_eq!(
wire.wait(published)["params"],
json!({"uri": uri(&file), "version": 1, "diagnostics": []})
);
}
#[test]
fn pull_result_ids_code_actions_and_same_version_reopen() {
let caps = json!({
"workspace": {"diagnostics": {"refreshSupport": true}, "workspaceEdit": {"documentChanges": true}},
"textDocument": {"diagnostic": {}, "codeAction": {
"codeActionLiteralSupport": {"codeActionKind": {"valueSet": ["quickfix", "refactor.rewrite"]}},
"dataSupport": true,
"resolveSupport": {"properties": ["edit"]}
}}
});
let mut wire = Session::start(caps, false, None);
let file = wire.file("sample.el");
let text = format!("{HEADER}(defun one (x) x)\n(let ((unused 0)) (one))\n");
wire.open(&file, 1, &text);
let refresh = wire.wait(|message| message["method"] == "workspace/diagnostic/refresh");
wire.send(json!({"jsonrpc": "2.0", "id": refresh["id"], "result": null}));
let first = wire.pull(&file, None);
let id = &first["resultId"];
code(items(&first["items"]), "arity");
let unused = code(items(&first["items"]), "unused-local");
assert_eq!(
wire.pull(&file, Some(id)),
json!({"kind": "unchanged", "resultId": id})
);
let actions = wire.call(
"textDocument/codeAction",
json!({
"textDocument": {"uri": uri(&file)},
"range": unused["range"],
"context": {"diagnostics": [unused], "only": ["quickfix"]}
}),
);
let action = &items(&actions["result"])[0];
assert!(action.get("edit").is_none());
let resolved = wire.call("codeAction/resolve", action.clone());
assert_eq!(
resolved["result"]["edit"]["documentChanges"][0]["edits"][0]["newText"],
"_unused"
);
wire.document_notification("textDocument/didClose", &file);
wire.open(&file, 1, "(defun one (x) x)\n(one 1)\n");
assert_eq!(
wire.call("codeAction/resolve", action.clone())["error"]["code"],
-32801
);
let current = wire.pull(&file, Some(id));
assert_eq!(current["kind"], "full");
assert!(items(¤t["items"]).is_empty());
assert_ne!(¤t["resultId"], id);
assert!(!wire.messages.iter().any(published));
}
#[test]
fn footer_cookie_is_an_explicit_refactor() {
let mut wire = Session::start(json!({"textDocument": {"diagnostic": {}}}), false, None);
let file = wire.file("sample.el");
wire.open(
&file,
0,
"#!/bin/sh\n(message \"hi\")\n;; Local Variables:\n;; lexical-binding: t\n;; End:\n",
);
let report = wire.pull(&file, None);
let footer = code(items(&report["items"]), "footer-lexical-binding");
let params = json!({
"textDocument": {"uri": uri(&file)},
"range": footer["range"],
"context": {"diagnostics": [footer], "only": ["quickfix"]}
});
assert_eq!(
wire.call("textDocument/codeAction", params.clone())["result"],
json!([])
);
let mut params = params;
params["context"]["only"] = json!(["refactor"]);
let actions = wire.call("textDocument/codeAction", params);
let action = &items(&actions["result"])[0];
assert_eq!(action["kind"], "refactor.rewrite");
assert_eq!(
action["edit"]["changes"][uri(&file)][0]["range"]["start"]["line"],
1
);
}
fn eval_diagnostics(message: &Value) -> bool {
published(message)
&& items(&message["params"]["diagnostics"]).iter().any(|item| {
matches!(
item["source"].as_str(),
Some("elsmith-bytecomp" | "elsmith-checkdoc" | "elsmith-package-lint")
)
})
}
#[test]
fn byte_compile_and_checkdoc_report_structured_ranges_and_no_elc() {
let Some(emacs) = emacs() else {
return;
};
let mut wire = Session::start(
json!({"window": {"workDoneProgress": true}}),
true,
Some(&emacs),
);
let file = wire.file("sample.el");
let text = format!("{HEADER}(defun els-test ()\n \"bad doc\"\n \"日本😀\" els-unknown)\n");
fs::write(&file, &text).unwrap();
wire.open(&file, 1, &text);
wire.document_notification("textDocument/didSave", &file);
let create = wire.wait(progress_create);
wire.send(json!({"jsonrpc": "2.0", "id": create["id"], "result": null}));
let result = wire.wait(eval_diagnostics);
let diagnostics = items(&result["params"]["diagnostics"]);
let compiled = diagnostics
.iter()
.find(|item| {
item["source"] == "elsmith-bytecomp"
&& item["message"]
.as_str()
.is_some_and(|message| message.contains("els-unknown"))
})
.unwrap();
assert_eq!(
compiled["range"]["start"],
json!({"line": 3, "character": 9})
);
assert!(
diagnostics
.iter()
.any(|item| item["source"] == "elsmith-checkdoc")
);
assert!(!file.with_extension("elc").exists());
assert!(
wire.messages.iter().any(
|item| item["method"] == "$/progress" && item["params"]["value"]["kind"] == "begin"
)
);
assert!(
wire.messages
.iter()
.any(|item| item["method"] == "$/progress" && item["params"]["value"]["kind"] == "end")
);
wire.revoke();
assert!(!eval_diagnostics(&wire.wait(published)));
}
#[test]
fn project_macros_expand_on_demand_and_cache_the_result() {
let Some(emacs) = emacs() else {
return;
};
let mut wire = Session::start(
json!({"window": {"workDoneProgress": true}}),
true,
Some(&emacs),
);
let file = wire.file("sample.el");
let text = format!("{HEADER}(defmacro els-twice (x) (list 'progn x x))\n(els-twice 7)\n");
fs::write(&file, &text).unwrap();
wire.open(&file, 1, &text);
let params = json!({"command": "elsmith.expandMacro", "arguments": [{
"uri": uri(&file), "position": {"line": 2, "character": 2}
}]});
let id = wire.request("workspace/executeCommand", params.clone());
let create = wire.wait(progress_create);
wire.send(json!({"jsonrpc": "2.0", "id": create["id"], "error": {"code": -32601, "message": "Unsupported"}}));
assert_eq!(
wire.wait(|message| message["id"] == id)["result"],
json!({"once": "(progn 7 7)", "all": "(progn 7 7)"})
);
assert_eq!(
wire.call("workspace/executeCommand", params.clone())["result"]["once"],
"(progn 7 7)"
);
assert_eq!(
wire.messages
.iter()
.filter(|message| progress_create(message))
.count(),
1
);
assert!(
!wire
.messages
.iter()
.any(|message| message["method"] == "$/progress")
);
wire.revoke();
assert!(
wire.call("workspace/executeCommand", params)
.get("error")
.is_some()
);
}
fn run_pass(emacs: &Path, package: Option<&str>) -> Value {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("sample.el");
fs::write(&file, format!("{HEADER}(message \"hello\")\n")).unwrap();
if let Some(package) = package {
fs::write(dir.path().join("package-lint.el"), package).unwrap();
}
fs::write(
dir.path().join("pass.el"),
include_bytes!("../src/oracle/pass.el"),
)
.unwrap();
fs::write(
dir.path().join("request.json"),
json!({
"file": file, "loadPaths": [dir.path()]
})
.to_string(),
)
.unwrap();
let output = Command::new(emacs)
.args(["-Q", "--batch", "-l", "pass.el"])
.current_dir(dir.path())
.env_clear()
.env("HOME", dir.path())
.output()
.unwrap();
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
serde_json::from_slice(&fs::read(dir.path().join("result.json")).unwrap()).unwrap()
}
#[test]
fn optional_package_lint_distinguishes_missing_empty_findings_and_failure() {
let Some(emacs) = emacs() else {
return;
};
let missing = run_pass(&emacs, None);
assert_eq!(
missing["packageLint"],
json!({"status": "missing", "findings": []})
);
let empty = run_pass(
&emacs,
Some("(defun package-lint-buffer () nil) (provide 'package-lint)"),
);
assert_eq!(
empty["packageLint"],
json!({"status": "ok", "findings": []})
);
let finding = run_pass(
&emacs,
Some(
"(defun package-lint-buffer () '((2 3 warning \"A lint finding\"))) (provide 'package-lint)",
),
);
assert_eq!(finding["packageLint"]["status"], "ok");
assert_eq!(
finding["packageLint"]["findings"][0]["message"],
"A lint finding"
);
assert_eq!(
finding["packageLint"]["findings"][0]["start"],
HEADER.chars().count() + 3
);
let failed = run_pass(
&emacs,
Some("(defun package-lint-buffer () (error \"lint failed\")) (provide 'package-lint)"),
);
assert_eq!(
failed["packageLint"],
json!({"status": "failed", "findings": [], "message": "lint failed"})
);
}
#[cfg(target_os = "linux")]
struct DelayedEmacs {
temp: tempfile::TempDir,
emacs: PathBuf,
}
#[cfg(target_os = "linux")]
impl DelayedEmacs {
fn new(emacs: &Path) -> Self {
use std::os::unix::fs::PermissionsExt;
let temp = tempfile::tempdir().unwrap();
let script = temp.path().join("emacs");
let path = env::var_os("PATH").unwrap();
let tool = |name| {
env::split_paths(&path)
.map(|dir| dir.join(name))
.find(|path| path.is_absolute() && path.is_file())
.unwrap()
};
let marker = temp.path().join("spawned");
let result = json!({
"byteCompile": [{"source": "elsmith-bytecomp", "start": 0, "severity": 2, "message": "delayed result"}],
"checkdoc": [], "packageLint": {"status": "missing", "findings": []}
});
fs::write(
&script,
format!(
"#!{shell}\nif [ \"$4\" != ./pass.el ]; then exec '{emacs}' \"$@\"; fi\n\
'{sleep}' 120 &\nchild=$!\n\
printf '%s %s\\n' \"$$\" \"$child\" >> '{marker}'\n\
printf '%s' '{result}' > result.json\n\
wait \"$child\"\n",
shell = tool("sh").display(),
emacs = emacs.display(),
sleep = tool("sleep").display(),
marker = marker.display(),
),
)
.unwrap();
fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap();
Self {
temp,
emacs: script,
}
}
fn pids(&self) -> Vec<libc::pid_t> {
fs::read_to_string(self.temp.path().join("spawned"))
.unwrap_or_default()
.split_whitespace()
.map(|pid| pid.parse().unwrap())
.collect()
}
}
#[cfg(target_os = "linux")]
fn until(mut finished: impl FnMut() -> bool) {
let deadline = Instant::now() + WAIT;
while !finished() {
assert!(Instant::now() < deadline, "condition did not become true");
std::thread::sleep(Duration::from_millis(20));
}
}
#[cfg(target_os = "linux")]
fn gone(pids: &[libc::pid_t]) -> bool {
pids.iter()
.all(|pid| !Path::new("/proc").join(pid.to_string()).exists())
}
#[cfg(target_os = "linux")]
fn start_delayed(wire: &mut Session, file: &Path, oracle: &DelayedEmacs) -> Vec<libc::pid_t> {
let previous = oracle.pids().len();
wire.document_notification("textDocument/didSave", file);
wire.wait(progress_create);
until(|| oracle.pids().len() == previous + 2);
oracle.pids()[previous..].to_vec()
}
#[cfg(target_os = "linux")]
#[test]
fn delayed_jobs_are_killed_on_change_reopen_revocation_and_parent_exit() {
let Some(emacs) = emacs() else {
return;
};
let fake = DelayedEmacs::new(&emacs);
let mut wire = Session::start(
json!({
"window": {"workDoneProgress": true},
"textDocument": {"diagnostic": {}}
}),
true,
Some(&fake.emacs),
);
let file = wire.file("sample.el");
let text = format!("{HEADER}(message \"hello\")\n");
fs::write(&file, &text).unwrap();
wire.open(&file, 3, &text);
let pids = start_delayed(&mut wire, &file, &fake);
wire.change(&file, 4, &text);
until(|| gone(&pids));
let pids = start_delayed(&mut wire, &file, &fake);
wire.document_notification("textDocument/didClose", &file);
wire.open(&file, 4, &text);
until(|| gone(&pids));
let first = wire.pull(&file, None);
assert_eq!(first["items"], json!([]));
let pids = start_delayed(&mut wire, &file, &fake);
wire.revoke();
until(|| gone(&pids));
assert_eq!(
wire.pull(&file, Some(&first["resultId"]))["kind"],
"unchanged"
);
assert!(!wire.messages.iter().any(published));
let config = wire.dir.path().join("config");
Allowlist::add(&config, &wire.dir.path().join("workspace")).unwrap();
wire.notify("workspace/didChangeConfiguration", json!({"settings": {}}));
let pids = start_delayed(&mut wire, &file, &fake);
wire.child.kill().unwrap();
wire.child.wait().unwrap();
until(|| gone(&pids));
}
#[cfg(target_os = "linux")]
#[test]
fn jobs_defer_for_dirty_siblings_and_untrusted_workspaces_never_spawn_them() {
let Some(emacs) = emacs() else {
return;
};
let fake = DelayedEmacs::new(&emacs);
let capabilities = json!({"window": {"workDoneProgress": true}});
{
let mut wire = Session::start(capabilities.clone(), false, Some(&fake.emacs));
let file = wire.file("sample.el");
let text = format!("{HEADER}(message \"hello\")\n");
fs::write(&file, &text).unwrap();
wire.open(&file, 1, &text);
wire.document_notification("textDocument/didSave", &file);
wire.call(
"textDocument/diagnostic",
json!({"textDocument": {"uri": uri(&file)}}),
);
wire.drain(Duration::from_millis(400));
assert!(!wire.messages.iter().any(progress_create));
assert!(fake.pids().is_empty());
}
let mut wire = Session::start(capabilities, true, Some(&fake.emacs));
let dep = wire.file("els-dep.el");
let file = wire.file("sample.el");
let dependency = format!("{HEADER}(provide 'els-dep)\n");
let dirty = format!("{dependency}(defvar els-dep-dirty)\n");
let text = format!("{HEADER}(require 'els-dep)\n");
fs::write(&dep, &dependency).unwrap();
fs::write(&file, &text).unwrap();
wire.open(&dep, 1, &dirty);
wire.open(&file, 1, &text);
wire.document_notification("textDocument/didSave", &file);
wire.call(
"textDocument/diagnostic",
json!({"textDocument": {"uri": uri(&file)}}),
);
wire.drain(Duration::from_millis(400));
assert!(!wire.messages.iter().any(progress_create));
assert!(fake.pids().is_empty());
fs::write(&dep, &dirty).unwrap();
wire.notify(
"workspace/didChangeWatchedFiles",
json!({
"changes": [{"uri": uri(&dep), "type": 2}]
}),
);
let create = wire.wait(progress_create);
wire.send(json!({"jsonrpc": "2.0", "id": create["id"], "result": null}));
wire.wait(|message| message["method"] == "$/progress");
until(|| fake.pids().len() == 2);
wire.notify(
"window/workDoneProgress/cancel",
json!({"token": create["params"]["token"]}),
);
until(|| gone(&fake.pids()));
assert!(!wire.messages.iter().any(eval_diagnostics));
}
#[test]
fn static_symbol_diagnostics_offer_a_require_only_for_a_resolved_provider() {
let Some(emacs) = emacs() else {
return;
};
let mut wire = Session::start(
json!({"textDocument": {"diagnostic": {}}}),
false,
Some(&emacs),
);
let file = wire.file("sample.el");
let dependency = wire.file("els-lib.el");
let provider = format!("{HEADER}(defun els-lib-hello () 0)\n(provide 'els-lib)\n");
fs::write(&dependency, &provider).unwrap();
let text = format!("{HEADER}(els-lib-hello)\n(els-diagnostic-unknown)\n");
wire.open(&file, 1, &text);
wire.call(
"textDocument/hover",
json!({
"textDocument": {"uri": uri(&file)}, "position": {"line": 1, "character": 2}
}),
);
let report = wire.pull(&file, None);
let diagnostics = items(&report["items"]);
code(diagnostics, "unbound-symbol");
let missing = code(diagnostics, "missing-require");
let actions = wire.call(
"textDocument/codeAction",
json!({
"textDocument": {"uri": uri(&file)}, "range": missing["range"],
"context": {"only": ["quickfix"], "diagnostics": [missing]}
}),
);
assert_eq!(items(&actions["result"]).len(), 1);
assert_eq!(
actions["result"][0]["edit"]["changes"][uri(&file)][0]["newText"],
"(require 'els-lib)\n\n"
);
let workspace = wire.call(
"workspace/diagnostic",
json!({
"previousResultIds": [{"uri": uri(&file), "value": report["resultId"]}]
}),
);
let docs = items(&workspace["result"]["items"]);
assert!(docs.iter().any(|item| item["uri"] == uri(&file)
&& item["version"] == 1
&& item["kind"] == "unchanged"));
assert!(
docs.iter()
.any(|item| item["uri"] == uri(&dependency) && item["version"].is_null())
);
}
#[cfg(target_os = "linux")]
#[test]
fn timeout_and_shutdown_reap_the_emacs_process_group() {
let Some(emacs) = emacs() else {
return;
};
let fake = DelayedEmacs::new(&emacs);
let mut wire = Session::start(
json!({"window": {"workDoneProgress": true}}),
true,
Some(&fake.emacs),
);
let file = wire.file("sample.el");
let text = format!("{HEADER}(message \"hello\")\n");
fs::write(&file, &text).unwrap();
wire.open(&file, 1, &text);
let start = Instant::now();
let pids = start_delayed(&mut wire, &file, &fake);
until(|| gone(&pids));
assert!(start.elapsed() >= Duration::from_secs(10));
let pids = start_delayed(&mut wire, &file, &fake);
assert_eq!(wire.call("shutdown", Value::Null)["result"], Value::Null);
wire.notify("exit", Value::Null);
assert!(wire.child.wait().unwrap().success());
assert!(gone(&pids));
assert!(!wire.messages.iter().any(eval_diagnostics));
}