Lutra/crates/control/tests/lsp.rs
danny 13c76d3046 M3.3: engine wiring for Phpactor and diagnostics
- One Phpactor per open project on its own session thread, started when
  the toolchain is ready; ordered document sync from buffer.edit and the
  pump; lspStatus, diagnosticsChanged, diagnostics.list, lsp.status,
  lsp.restart; app.quit stops the server synchronously.
- Phpactor 2026.06.25.0 on Windows: keep-alive $/lutra/tick (its event
  loop only runs on stdin input), in-process diagnostics and a polling
  watcher through initializationOptions (amphp subprocesses fail), 500 ms
  shutdown timeout.
- Editor lint extension (underlines, gutter dots, hover; tokens only) and
  a Problems tab in the bottom panel; problems.open Mod+Alt+P.
- Tests: engine tests against the fake server (incl. sync proptest), an
  ignored real-Phpactor test, a TCP test, Vitest for lint and Problems.
- Docs: architecture, gaps G6, parity (Inspections 4% est.), ui-parity,
  roadmap, ROADMAP.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 18:58:32 +02:00

192 lines
6.1 KiB
Rust

//! The language server wiring over a real TCP control connection:
//! `lspStatus` and `diagnosticsChanged` arrive as events while a buffer is
//! edited, and `diagnostics.list` / `lsp.status` answer from the engine.
//! The server is M3.2's fake, which publishes each document's text as its
//! one diagnostic.
#![allow(
clippy::unwrap_used,
clippy::expect_used,
clippy::indexing_slicing,
clippy::panic
)]
use std::io::{BufRead, BufReader, Write};
use std::net::TcpStream;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
use lutra_engine::Engine;
use lutra_engine::lsp::{Launch, ServerOptions};
use lutra_testkit::EngineBackend;
use serde_json::{Value, json};
/// A client that keeps responses and event lines apart.
struct Client {
reader: BufReader<TcpStream>,
writer: TcpStream,
events: Vec<Value>,
}
impl Client {
fn connect(addr: std::net::SocketAddr) -> Self {
let stream = TcpStream::connect(addr).unwrap();
stream
.set_read_timeout(Some(Duration::from_secs(30)))
.unwrap();
Self {
writer: stream.try_clone().unwrap(),
reader: BufReader::new(stream),
events: Vec::new(),
}
}
fn line(&mut self) -> Value {
let mut line = String::new();
self.reader.read_line(&mut line).expect("line within 30 s");
serde_json::from_str(&line).unwrap()
}
fn call(&mut self, request: Value) -> Value {
self.writer
.write_all(format!("{request}\n").as_bytes())
.unwrap();
loop {
let line = self.line();
if line.get("event").is_some() {
self.events.push(line["event"].clone());
} else {
return line;
}
}
}
/// The next event (queued or read) for which `pick` holds.
fn event(&mut self, pick: impl Fn(&Value) -> bool) -> Value {
if let Some(i) = self.events.iter().position(&pick) {
return self.events.remove(i);
}
loop {
let line = self.line();
if let Some(event) = line.get("event") {
if pick(event) {
return event.clone();
}
self.events.push(event.clone());
}
}
}
}
fn execute(command: &str, params: Value) -> Value {
json!({"id": command, "method": "engine.execute", "params": {"command": command, "params": params}})
}
/// Pumps the backend every 20 ms, like the desktop's pump thread, until
/// dropped.
struct Pump(Arc<AtomicBool>);
impl Pump {
fn start(backend: Arc<EngineBackend>) -> Self {
let stop = Arc::new(AtomicBool::new(false));
let flag = stop.clone();
std::thread::spawn(move || {
while !flag.load(Ordering::Relaxed) {
backend.pump();
std::thread::sleep(Duration::from_millis(20));
}
});
Self(stop)
}
}
impl Drop for Pump {
fn drop(&mut self) {
self.0.store(true, Ordering::Relaxed);
}
}
/// The fake server binary, built on demand when this test runs alone.
fn fake_server() -> std::path::PathBuf {
let exe = format!("lutra-lsp-fake{}", std::env::consts::EXE_SUFFIX);
let deps = std::env::current_exe().unwrap();
let path = deps.parent().unwrap().parent().unwrap().join(exe);
if !path.exists() {
let cargo = std::env::var_os("CARGO").unwrap_or_else(|| "cargo".into());
let status = std::process::Command::new(cargo)
.args(["build", "-p", "lutra-lsp", "--bin", "lutra-lsp-fake"])
.status()
.unwrap();
assert!(status.success(), "building lutra-lsp-fake failed");
}
path
}
#[test]
fn diagnostics_over_tcp() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(
dir.path().join("a.php"),
"<?php
",
)
.unwrap();
let mut engine = Engine::new().unwrap();
engine.set_language_server(Some(Launch {
command: fake_server().into(),
args: Vec::new(),
options: ServerOptions::default(),
tick: Some(std::time::Duration::from_millis(50)),
}));
let backend = Arc::new(EngineBackend::with_engine(engine));
let server = lutra_control::start(0, backend.clone()).unwrap();
let mut client = Client::connect(server.local_addr());
client.call(json!({"id": 1, "method": "events.subscribe"}));
let _pump = Pump::start(backend.clone());
let r = client.call(execute("project.open", json!({"path": dir.path()})));
assert!(r["error"].is_null(), "{r}");
client.event(|e| e["kind"] == "lspStatus" && e["state"] == "starting");
client.event(|e| e["kind"] == "lspStatus" && e["state"] == "ready");
let r = client.call(execute("lsp.status", Value::Null));
assert_eq!(r["result"]["state"], "ready", "{r}");
let r = client.call(execute("file.open", json!({"path": "a.php"})));
let id = r["result"]["id"].as_u64().unwrap();
let first = client.event(|e| e["kind"] == "diagnosticsChanged");
assert_eq!(first["path"], "a.php");
assert_eq!(
first["items"][0]["message"],
"<?php
"
);
let r = client.call(execute(
"buffer.edit",
json!({"id": id, "baseVersion": 1, "edits": [{"from": 6, "to": 6, "insert": "echo 1;"}]}),
));
assert!(r["error"].is_null(), "{r}");
let changed = client.event(|e| {
e["kind"] == "diagnosticsChanged"
&& e["items"][0]["message"]
== "<?php
echo 1;"
});
assert_eq!(changed["items"][0]["severity"], "error");
assert_eq!(
changed["items"][0]["range"],
json!({"start": {"line": 0, "column": 0}, "end": {"line": 0, "column": 0}})
);
let r = client.call(execute("diagnostics.list", json!({})));
assert_eq!(r["result"]["files"][0]["path"], "a.php", "{r}");
assert_eq!(
r["result"]["files"][0]["items"][0]["message"],
"<?php
echo 1;"
);
let r = client.call(execute("project.close", json!({"force": true})));
assert!(r["error"].is_null(), "{r}");
client.event(|e| e["kind"] == "lspStatus" && e["state"] == "stopped");
}