- Session tick: 1 ms while Phpactor reports work-done progress and in a
session's first 120 s, otherwise 25 ms as before. Fast intervals use
thread::sleep, because recv_timeout wakes at most ~64/s on Windows.
First useful completion on 2,000 classes: 71.6 s -> 20.7-26.9 s.
- $/progress -> lspProgress {active, title?, message?, percentage?},
progress in lsp.status, a status-bar item (LspProgressItem).
- window/showMessage -> notification.lsp.message (repeats within 30 s and
the known Windows lint-provider complaint only logged); showMessage,
logMessage and stderr in a 1,000-line log, new command lsp.log.
- Lutra's own php -l on Windows (lsp/php_lint.rs): on open and save, one
worker thread, lutra_proc::spawn, stdin, 10 s timeout, output caps;
merged into diagnosticsChanged with source "php -l".
- editor.completion.delayMs stays 0 (measured: 100 ms only delays the
list; Phpactor marks every list incomplete).
- Fake server: scripted notifications after initialized.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
428 lines
17 KiB
Rust
428 lines
17 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/completion` a scripted list (see [`completion`]),
|
|
//! `textDocument/signatureHelp` one signature whose active parameter is
|
|
//! the column modulo 2,
|
|
//! `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.
|
|
//! - `--script FILE` reads a JSON object
|
|
//! `{capabilities?, responses?, notifications?}`: `capabilities` are
|
|
//! merged into the `initialize` answer, `responses` maps a request
|
|
//! method to the result it gets, before the built-in answers (M3.5:
|
|
//! references, prepareRename, rename), and `notifications`
|
|
//! (`[{method, params}]`) are sent in order after `initialized` (H3:
|
|
//! messages and progress).
|
|
|
|
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,
|
|
/// The `--script` file's content, `null` without one.
|
|
script: Value,
|
|
}
|
|
|
|
/// The fake answer to `textDocument/completion`: a `CompletionList` whose
|
|
/// first item replaces the word before the cursor through a `textEdit`
|
|
/// (with an import as `additionalTextEdits`), then a plain variable, a
|
|
/// snippet and an item echoing the trigger character. A document
|
|
/// containing `MANY` gets 700 numbered items instead.
|
|
fn completion(text: &str, position: &Value, context: &Value) -> Value {
|
|
if text.contains("MANY") {
|
|
let items: Vec<Value> = (0..700)
|
|
.map(|i| json!({"label": format!("item{i:03}"), "kind": 6}))
|
|
.collect();
|
|
return json!({"isIncomplete": false, "items": items});
|
|
}
|
|
let line = at(position, "/line").as_u64().unwrap_or(0);
|
|
let character = at(position, "/character").as_u64().unwrap_or(0);
|
|
let trigger = at(context, "/triggerCharacter").as_str().unwrap_or("none");
|
|
json!({
|
|
"isIncomplete": true,
|
|
"items": [
|
|
{
|
|
"label": "format",
|
|
"kind": 2,
|
|
"detail": "format(string $pattern): string",
|
|
"documentation": {"kind": "markdown", "value": "Formats **text**."},
|
|
"sortText": "0001",
|
|
"textEdit": {
|
|
"range": {"start": {"line": line, "character": character.saturating_sub(2)}, "end": {"line": line, "character": character}},
|
|
"newText": "format("
|
|
},
|
|
"additionalTextEdits": [{
|
|
"range": {"start": {"line": 0, "character": 5}, "end": {"line": 0, "character": 5}},
|
|
"newText": "\nuse App\\Fmt;"
|
|
}]
|
|
},
|
|
{"label": "$value", "kind": 6, "sortText": "0002"},
|
|
{"label": "pair", "kind": 3, "insertTextFormat": 2, "insertText": "pair(${1:\\$a}, $2)$0", "sortText": "0003"},
|
|
{"label": format!("trigger:{trigger}"), "kind": 14, "sortText": "0004"}
|
|
]
|
|
})
|
|
}
|
|
|
|
/// 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"),
|
|
script: script(&args),
|
|
};
|
|
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);
|
|
}
|
|
}
|
|
}
|
|
|
|
/// The JSON in the file after `--script`, `null` without one; exits with 4
|
|
/// when it cannot be read.
|
|
fn script(args: &[String]) -> Value {
|
|
let Some(at) = args.iter().position(|a| a == "--script") else {
|
|
return Value::Null;
|
|
};
|
|
let Some(path) = args.get(at + 1) else {
|
|
exit(4);
|
|
};
|
|
match std::fs::read_to_string(path).map(|text| serde_json::from_str(&text)) {
|
|
Ok(Ok(value)) => value,
|
|
_ => exit(4),
|
|
}
|
|
}
|
|
|
|
/// 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) {
|
|
if let Some(result) = self
|
|
.script
|
|
.pointer(&format!("/responses/{}", method.replace('/', "~1")))
|
|
{
|
|
respond(id, Ok(result.clone()));
|
|
return;
|
|
}
|
|
match method {
|
|
"initialize" if self.init_error => respond(id, Err(error(-32002, "no init"))),
|
|
"initialize" => {
|
|
let change = if self.full_sync { 1 } else { 2 };
|
|
let mut capabilities = json!({
|
|
"positionEncoding": "utf-16",
|
|
"textDocumentSync": {"openClose": true, "change": change, "save": {"includeText": true}},
|
|
"hoverProvider": true,
|
|
"definitionProvider": true,
|
|
"completionProvider": {"triggerCharacters": [">", ":", "$", "\\"]},
|
|
"signatureHelpProvider": {"triggerCharacters": ["(", ","]}
|
|
});
|
|
if let (Some(all), Some(extra)) = (
|
|
capabilities.as_object_mut(),
|
|
self.script.get("capabilities").and_then(Value::as_object),
|
|
) {
|
|
all.extend(extra.clone());
|
|
}
|
|
respond(
|
|
id,
|
|
Ok(json!({"capabilities": capabilities, "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}}])),
|
|
);
|
|
}
|
|
"textDocument/completion" => {
|
|
let uri = at(params, "/textDocument/uri").as_str().unwrap_or_default();
|
|
let text = self
|
|
.documents
|
|
.get(uri)
|
|
.map(Buffer::text)
|
|
.unwrap_or_default();
|
|
respond(
|
|
id,
|
|
Ok(completion(
|
|
&text,
|
|
at(params, "/position"),
|
|
at(params, "/context"),
|
|
)),
|
|
);
|
|
}
|
|
"textDocument/signatureHelp" => {
|
|
let position = at(params, "/position");
|
|
let active = at(position, "/character").as_u64().unwrap_or(0) % 2;
|
|
respond(
|
|
id,
|
|
Ok(json!({
|
|
"signatures": [{
|
|
"label": "pair(int $a, string $b): void",
|
|
"documentation": {"kind": "markdown", "value": "Makes a *pair*."},
|
|
"parameters": [{"label": "int $a"}, {"label": [13, 22]}]
|
|
}],
|
|
"activeSignature": 0,
|
|
"activeParameter": active
|
|
})),
|
|
);
|
|
}
|
|
"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"}));
|
|
let scripted = self
|
|
.script
|
|
.get("notifications")
|
|
.and_then(Value::as_array)
|
|
.cloned()
|
|
.unwrap_or_default();
|
|
for n in scripted {
|
|
notify(
|
|
at(&n, "/method").as_str().unwrap_or_default(),
|
|
at(&n, "/params").clone(),
|
|
);
|
|
}
|
|
}
|
|
"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)
|
|
}
|