crates/lsp is now a library: Content-Length JSON-RPC framing over stdio (32 MiB cap, malformed frames dropped and reported, fuzzed), Server::spawn with initialize/initialized (utf-16, incremental sync, completion, hover, signatureHelp, definition, references, rename, publishDiagnostics), typed requests with timeouts and $/cancelRequest, answers to server requests (configuration nulls, MethodNotFound), events on a bounded channel, supervision with backoff restarts that reopen documents and give up after 5 crashes in 2 min, shutdown/exit, and incremental document sync from lutra_text edits. Tested against a scripted fake server binary; docs: architecture, G6. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
303 lines
12 KiB
Rust
303 lines
12 KiB
Rust
//! A scripted fake language server for the `lutra-lsp` tests.
|
|
//!
|
|
//! Not shipped: the integration tests start it through
|
|
//! `CARGO_BIN_EXE_lutra-lsp-fake`. It speaks LSP over stdio with the
|
|
//! client's own framing and behaves predictably:
|
|
//!
|
|
//! - `initialize` announces incremental sync (`--sync-full` for full sync)
|
|
//! and save with text; `--exit-immediately` exits before reading anything,
|
|
//! `--init-error` answers `initialize` with an error.
|
|
//! - After `initialized` it sends three requests to the client
|
|
//! (`workspace/configuration` with two items, an unknown method,
|
|
//! `window/workDoneProgress/create`) and reports the answers as the
|
|
//! notification `fake/serverResponses`; it also logs `hello`.
|
|
//! - Every `didOpen`/`didChange` applies the change to its own copy and
|
|
//! publishes one diagnostic whose message is the whole text, with the
|
|
//! document version; `didClose` publishes no diagnostics; `didSave` sends
|
|
//! `fake/saved` with the text it received.
|
|
//! - Requests: `textDocument/hover` answers `hover L:C`,
|
|
//! `textDocument/definition` the same position, `fake/echo` its params,
|
|
//! `fake/error` an error, `fake/sleep` never answers until cancelled
|
|
//! (then `RequestCancelled` and the notification `fake/cancelled`),
|
|
//! `fake/crash` exits with code 7, `fake/garbage` writes malformed frames
|
|
//! before answering. `shutdown` answers `null`; `exit` exits with 0.
|
|
|
|
use std::collections::HashMap;
|
|
use std::io::{self, BufReader, Write};
|
|
use std::process::exit;
|
|
|
|
use lutra_lsp::jsonrpc::{
|
|
self, Frame, MAX_MESSAGE_BYTES, METHOD_NOT_FOUND, Message, REQUEST_CANCELLED, ResponseError,
|
|
};
|
|
use lutra_lsp::types::position_from_json;
|
|
use lutra_text::{Buffer, ColumnUnit, Edit};
|
|
use serde_json::{Value, json};
|
|
|
|
/// The fake server's state.
|
|
struct Fake {
|
|
/// Documents by URI.
|
|
documents: HashMap<String, Buffer>,
|
|
/// Ids of `fake/sleep` requests not yet cancelled.
|
|
sleeping: Vec<Value>,
|
|
/// Answers to the server's own requests, by id.
|
|
responses: Vec<(Value, Value)>,
|
|
/// Whether changes are full-text only.
|
|
full_sync: bool,
|
|
/// Whether `initialize` fails.
|
|
init_error: bool,
|
|
}
|
|
|
|
/// Runs the fake server until `exit` or the end of stdin.
|
|
fn main() {
|
|
let args: Vec<String> = std::env::args().skip(1).collect();
|
|
if args.iter().any(|a| a == "--exit-immediately") {
|
|
exit(3);
|
|
}
|
|
let _ = writeln!(io::stderr(), "fake server started");
|
|
let mut fake = Fake {
|
|
documents: HashMap::new(),
|
|
sleeping: Vec::new(),
|
|
responses: Vec::new(),
|
|
full_sync: args.iter().any(|a| a == "--sync-full"),
|
|
init_error: args.iter().any(|a| a == "--init-error"),
|
|
};
|
|
let mut reader = BufReader::new(io::stdin().lock());
|
|
while let Ok(Some(frame)) = jsonrpc::read_frame(&mut reader, MAX_MESSAGE_BYTES) {
|
|
let Frame::Body(body) = frame else {
|
|
continue;
|
|
};
|
|
if let Ok(message) = Message::parse(&body) {
|
|
fake.handle(message);
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Writes one message to stdout; exits if stdout is gone.
|
|
fn send(value: &Value) {
|
|
let mut stdout = io::stdout().lock();
|
|
if jsonrpc::write_frame(&mut stdout, value).is_err() {
|
|
exit(1);
|
|
}
|
|
}
|
|
|
|
/// Writes raw bytes to stdout.
|
|
fn send_raw(bytes: &[u8]) {
|
|
let mut stdout = io::stdout().lock();
|
|
if stdout
|
|
.write_all(bytes)
|
|
.and_then(|()| stdout.flush())
|
|
.is_err()
|
|
{
|
|
exit(1);
|
|
}
|
|
}
|
|
|
|
/// Sends a notification.
|
|
fn notify(method: &str, params: Value) {
|
|
send(&json!({"jsonrpc": "2.0", "method": method, "params": params}));
|
|
}
|
|
|
|
/// Sends a response.
|
|
fn respond(id: Value, result: Result<Value, ResponseError>) {
|
|
send(&Message::Response { id, result }.to_json());
|
|
}
|
|
|
|
/// An error response body.
|
|
fn error(code: i64, message: &str) -> ResponseError {
|
|
ResponseError {
|
|
code,
|
|
message: message.to_string(),
|
|
data: None,
|
|
}
|
|
}
|
|
|
|
impl Fake {
|
|
/// Handles one message from the client.
|
|
fn handle(&mut self, message: Message) {
|
|
match message {
|
|
Message::Request { id, method, params } => self.request(id, &method, ¶ms),
|
|
Message::Notification { method, params } => self.notification(&method, ¶ms),
|
|
Message::Response { id, result } => {
|
|
let value = match result {
|
|
Ok(value) => json!({"result": value}),
|
|
Err(e) => json!({"error": e.code}),
|
|
};
|
|
self.responses.push((id, value));
|
|
if self.responses.len() == 3 {
|
|
let all: Vec<Value> = self
|
|
.responses
|
|
.iter()
|
|
.map(|(id, value)| json!({"id": id, "answer": value}))
|
|
.collect();
|
|
notify("fake/serverResponses", json!({"responses": all}));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Answers a request.
|
|
fn request(&mut self, id: Value, method: &str, params: &Value) {
|
|
match method {
|
|
"initialize" if self.init_error => respond(id, Err(error(-32002, "no init"))),
|
|
"initialize" => {
|
|
let change = if self.full_sync { 1 } else { 2 };
|
|
respond(
|
|
id,
|
|
Ok(json!({
|
|
"capabilities": {
|
|
"positionEncoding": "utf-16",
|
|
"textDocumentSync": {"openClose": true, "change": change, "save": {"includeText": true}},
|
|
"hoverProvider": true,
|
|
"definitionProvider": true
|
|
},
|
|
"serverInfo": {"name": "fake"}
|
|
})),
|
|
);
|
|
}
|
|
"shutdown" => respond(id, Ok(Value::Null)),
|
|
"textDocument/hover" => {
|
|
let position = at(params, "/position");
|
|
respond(
|
|
id,
|
|
Ok(
|
|
json!({"contents": {"kind": "markdown", "value": format!("hover {}:{}", at(position, "/line"), at(position, "/character"))}}),
|
|
),
|
|
);
|
|
}
|
|
"textDocument/definition" => {
|
|
let uri = at(params, "/textDocument/uri").clone();
|
|
let position = at(params, "/position").clone();
|
|
respond(
|
|
id,
|
|
Ok(json!([{"uri": uri, "range": {"start": position, "end": position}}])),
|
|
);
|
|
}
|
|
"fake/echo" => respond(id, Ok(params.clone())),
|
|
"fake/error" => respond(id, Err(error(-32001, "boom"))),
|
|
"fake/sleep" => self.sleeping.push(id),
|
|
"fake/crash" => exit(7),
|
|
"fake/garbage" => {
|
|
send_raw(b"garbage line\r\n\r\n");
|
|
send_raw(b"Content-Length: 5\r\n\r\n{nope");
|
|
send_raw(b"Content-Type: x\r\n\r\n");
|
|
send_raw(b"Content-Length: 2\r\n\r\n[]");
|
|
respond(id, Ok(json!("after garbage")));
|
|
}
|
|
_ => respond(id, Err(error(METHOD_NOT_FOUND, "unknown"))),
|
|
}
|
|
}
|
|
|
|
/// Handles a notification.
|
|
fn notification(&mut self, method: &str, params: &Value) {
|
|
let uri = at(params, "/textDocument/uri")
|
|
.as_str()
|
|
.unwrap_or_default()
|
|
.to_string();
|
|
let version = at(params, "/textDocument/version").clone();
|
|
match method {
|
|
"initialized" => {
|
|
send(
|
|
&json!({"jsonrpc": "2.0", "id": "c1", "method": "workspace/configuration",
|
|
"params": {"items": [{"section": "a"}, {"section": "b"}]}}),
|
|
);
|
|
send(&json!({"jsonrpc": "2.0", "id": 2, "method": "fake/unknown", "params": {}}));
|
|
send(
|
|
&json!({"jsonrpc": "2.0", "id": 3, "method": "window/workDoneProgress/create",
|
|
"params": {"token": "t"}}),
|
|
);
|
|
notify("window/logMessage", json!({"type": 3, "message": "hello"}));
|
|
}
|
|
"exit" => exit(0),
|
|
"$/cancelRequest" => {
|
|
let id = at(params, "/id").clone();
|
|
if let Some(index) = self.sleeping.iter().position(|s| *s == id) {
|
|
self.sleeping.remove(index);
|
|
respond(id.clone(), Err(error(REQUEST_CANCELLED, "cancelled")));
|
|
notify("fake/cancelled", json!({"id": id}));
|
|
}
|
|
}
|
|
"textDocument/didOpen" => {
|
|
let text = at(params, "/textDocument/text")
|
|
.as_str()
|
|
.unwrap_or_default();
|
|
self.documents.insert(uri.clone(), Buffer::new(text));
|
|
self.publish(&uri, version);
|
|
}
|
|
"textDocument/didChange" => {
|
|
let changes = at(params, "/contentChanges")
|
|
.as_array()
|
|
.cloned()
|
|
.unwrap_or_default();
|
|
let outcome = self.apply(&uri, &changes);
|
|
match outcome {
|
|
Ok(()) => self.publish(&uri, version),
|
|
Err(message) => publish_text(&uri, version, &format!("ERROR: {message}")),
|
|
}
|
|
}
|
|
"textDocument/didSave" => {
|
|
notify(
|
|
"fake/saved",
|
|
json!({"uri": uri, "text": at(params, "/text")}),
|
|
);
|
|
}
|
|
"textDocument/didClose" => {
|
|
self.documents.remove(&uri);
|
|
notify(
|
|
"textDocument/publishDiagnostics",
|
|
json!({"uri": uri, "diagnostics": []}),
|
|
);
|
|
}
|
|
_ => {}
|
|
}
|
|
}
|
|
|
|
/// Applies content changes one after another.
|
|
fn apply(&mut self, uri: &str, changes: &[Value]) -> Result<(), String> {
|
|
let buffer = self.documents.get_mut(uri).ok_or("not open")?;
|
|
for change in changes {
|
|
let text = at(change, "/text").as_str().ok_or("no text")?;
|
|
if change.get("range").is_none() {
|
|
*buffer = Buffer::new(text);
|
|
continue;
|
|
}
|
|
let start = position_from_json(at(change, "/range/start")).ok_or("bad start")?;
|
|
let end = position_from_json(at(change, "/range/end")).ok_or("bad end")?;
|
|
let start = buffer
|
|
.position_to_offset(start, ColumnUnit::Utf16)
|
|
.map_err(|e| e.to_string())?;
|
|
let end = buffer
|
|
.position_to_offset(end, ColumnUnit::Utf16)
|
|
.map_err(|e| e.to_string())?;
|
|
buffer
|
|
.apply(&[Edit::replace(start..end, text)])
|
|
.map_err(|e| e.to_string())?;
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// Publishes the document's text as its one diagnostic.
|
|
fn publish(&self, uri: &str, version: Value) {
|
|
let text = self
|
|
.documents
|
|
.get(uri)
|
|
.map(Buffer::text)
|
|
.unwrap_or_default();
|
|
publish_text(uri, version, &text);
|
|
}
|
|
}
|
|
|
|
/// Publishes one diagnostic with `message`.
|
|
fn publish_text(uri: &str, version: Value, message: &str) {
|
|
notify(
|
|
"textDocument/publishDiagnostics",
|
|
json!({"uri": uri, "version": version, "diagnostics": [{
|
|
"range": {"start": {"line": 0, "character": 0}, "end": {"line": 0, "character": 0}},
|
|
"severity": 1, "source": "fake", "message": message
|
|
}]}),
|
|
);
|
|
}
|
|
|
|
/// The value at a JSON pointer, `null` when absent.
|
|
fn at<'a>(value: &'a Value, pointer: &str) -> &'a Value {
|
|
value.pointer(pointer).unwrap_or(&Value::Null)
|
|
}
|