Initial public release
Luxe 0.1.0: a coding agent harness for the terminal. See README.md to get started and CHANGELOG.md for releases.
This commit is contained in:
262
crates/luxe-lsp/src/client/diagnostics.rs
Normal file
262
crates/luxe-lsp/src/client/diagnostics.rs
Normal file
@@ -0,0 +1,262 @@
|
||||
//! Diagnostics — opening documents, and settling on what the server has to say about them.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Hash document content to a `u64` so an unchanged warm read can skip a resync.
|
||||
pub(super) fn hash_content(content: &str) -> u64 {
|
||||
let mut hasher = std::collections::hash_map::DefaultHasher::new();
|
||||
content.hash(&mut hasher);
|
||||
hasher.finish()
|
||||
}
|
||||
|
||||
/// Default budget for a cold `get_diagnostics` settle wait.
|
||||
pub(super) const DEFAULT_DIAGNOSTICS_WAIT: Duration = Duration::from_secs(10);
|
||||
/// Minimum time to give the server to react to a document open/change before settling.
|
||||
pub(super) const SETTLE_MIN_WAIT: Duration = Duration::from_millis(150);
|
||||
/// How long the diagnostics cache must be unchanged (and progress idle) to count as settled.
|
||||
pub(super) const SETTLE_QUIESCENCE: Duration = Duration::from_millis(250);
|
||||
/// After this long idle + quiescent with no publish at all, conclude "clean, nothing to report"
|
||||
/// rather than waiting the whole budget. A server still working holds `$/progress` tokens
|
||||
/// (progress_active > 0), so this only fires for a genuinely silent server.
|
||||
pub(super) const SETTLE_NO_PUBLISH_GRACE: Duration = Duration::from_millis(1500);
|
||||
|
||||
impl LspClient {
|
||||
/// Ensure a document is open and synced; returns `true` when a fresh publish should be awaited.
|
||||
///
|
||||
/// A brand-new document is opened (`didOpen`); a changed one is synced (`didChange`); an
|
||||
/// unchanged, already-open document returns `false` so a warm read can use the cache directly.
|
||||
pub(super) async fn ensure_document(
|
||||
&mut self,
|
||||
uri: &str,
|
||||
content: &str,
|
||||
) -> Result<bool, LspError> {
|
||||
let hash = hash_content(content);
|
||||
match self.open_docs.get(uri).copied() {
|
||||
Some((_, old_hash)) if old_hash == hash => return Ok(false),
|
||||
Some((version, _)) => {
|
||||
let version = version + 1;
|
||||
self.send_notification(
|
||||
"textDocument/didChange",
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri, "version": version },
|
||||
"contentChanges": [{ "text": content }]
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
self.open_docs.insert(uri.to_string(), (version, hash));
|
||||
}
|
||||
None => {
|
||||
self.send_notification(
|
||||
"textDocument/didOpen",
|
||||
serde_json::json!({
|
||||
"textDocument": {
|
||||
"uri": uri,
|
||||
"languageId": self.language_id_for(uri),
|
||||
"version": 1,
|
||||
"text": content
|
||||
}
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
self.open_docs.insert(uri.to_string(), (1, hash));
|
||||
}
|
||||
}
|
||||
// Reset quiescence from our own action so a silent-clean server still settles cleanly.
|
||||
self.shared.mark_change();
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Ensure a document is open (synced from the given content) so document-scoped requests
|
||||
/// (`documentSymbol`, navigation) resolve. Idempotent for unchanged content.
|
||||
pub async fn open_document(&mut self, uri: &str, content: &str) -> Result<(), LspError> {
|
||||
self.ensure_document(uri, content).await.map(|_| ())
|
||||
}
|
||||
|
||||
/// Wait until the server is ready to answer navigation/symbol requests.
|
||||
///
|
||||
/// Prefers rust-analyzer's `experimental/serverStatus { quiescent: true }`; for servers that
|
||||
/// don't send it, falls back to "no in-flight `$/progress` and quiet for a settle window".
|
||||
/// Returns immediately for a warm, already-quiescent server.
|
||||
pub async fn wait_until_idle(&self, wait: Duration) {
|
||||
const FALLBACK_QUIESCENCE: Duration = Duration::from_millis(1200);
|
||||
let start = Instant::now();
|
||||
loop {
|
||||
let (progress_active, quiescent, since_change) = {
|
||||
let inner = self.shared.inner.lock().expect("diagnostics state poisoned");
|
||||
(inner.progress_active, inner.quiescent, inner.since_change())
|
||||
};
|
||||
if quiescent || (progress_active == 0 && since_change >= FALLBACK_QUIESCENCE) {
|
||||
break;
|
||||
}
|
||||
if start.elapsed() >= wait {
|
||||
break;
|
||||
}
|
||||
tokio::select! {
|
||||
_ = self.shared.notify.notified() => {}
|
||||
_ = tokio::time::sleep(Duration::from_millis(80)) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Get diagnostics for a document, waiting up to the default budget for the server to settle.
|
||||
pub async fn get_diagnostics(
|
||||
&mut self,
|
||||
uri: &str,
|
||||
content: &str,
|
||||
) -> Result<Vec<Diagnostic>, LspError> {
|
||||
self.get_diagnostics_with_wait(uri, content, DEFAULT_DIAGNOSTICS_WAIT).await
|
||||
}
|
||||
|
||||
/// Get diagnostics for a document with an explicit settle budget.
|
||||
///
|
||||
/// Opens/syncs the document, then waits until the server is idle (no in-flight `$/progress`),
|
||||
/// the cache has been quiescent, and at least one publish arrived — or the budget elapses.
|
||||
/// A warm, unchanged document returns the cached result immediately. A server that has never
|
||||
/// published about this document and can be asked is asked, rather than reported as clean.
|
||||
pub async fn get_diagnostics_with_wait(
|
||||
&mut self,
|
||||
uri: &str,
|
||||
content: &str,
|
||||
wait: Duration,
|
||||
) -> Result<Vec<Diagnostic>, LspError> {
|
||||
if self.state != ClientState::Initialized {
|
||||
return Err(LspError::NotInitialized);
|
||||
}
|
||||
if !self.ensure_document(uri, content).await? {
|
||||
return Ok(self.cached_diagnostics(uri));
|
||||
}
|
||||
|
||||
let base_publish = self.publish_count();
|
||||
let start = Instant::now();
|
||||
loop {
|
||||
let (progress_active, since_change, publish_count) = {
|
||||
let inner = self.shared.inner.lock().expect("diagnostics state poisoned");
|
||||
(inner.progress_active, inner.since_change(), inner.publish_count)
|
||||
};
|
||||
let idle_quiescent = start.elapsed() >= SETTLE_MIN_WAIT
|
||||
&& progress_active == 0
|
||||
&& since_change >= SETTLE_QUIESCENCE;
|
||||
// Waiting out the no-publish grace is pointless when the answer is going to be asked
|
||||
// for: the request itself is the synchronization point, since the server holds it
|
||||
// until it can answer. Only the idle check still has to pass, so a server that is
|
||||
// still loading the project is not interrupted mid-index.
|
||||
let settled = idle_quiescent
|
||||
&& (publish_count > base_publish
|
||||
|| self.pulls_diagnostics_for(uri)
|
||||
|| start.elapsed() >= SETTLE_NO_PUBLISH_GRACE);
|
||||
if settled || start.elapsed() >= wait {
|
||||
break;
|
||||
}
|
||||
tokio::select! {
|
||||
_ = self.shared.notify.notified() => {}
|
||||
_ = tokio::time::sleep(Duration::from_millis(80)) => {}
|
||||
}
|
||||
}
|
||||
if self.pulls_diagnostics_for(uri) {
|
||||
// What is left of the caller's budget: the request is where a pull server does its
|
||||
// thinking, so it has to answer inside the window the settle loop would have spent.
|
||||
self.pull_document_diagnostics(uri, wait.saturating_sub(start.elapsed())).await;
|
||||
}
|
||||
Ok(self.cached_diagnostics(uri))
|
||||
}
|
||||
|
||||
/// Whether this document's diagnostics have to be asked for rather than waited on.
|
||||
///
|
||||
/// Push wins wherever it is offered: a server that has published about this file has answered,
|
||||
/// and asking again would only replace a settled answer with a second opinion — rust-analyzer
|
||||
/// advertises both and its pushed set is cargo's, which is the one a reader means. What is left
|
||||
/// is the file the server has said nothing about, which is where a pull-only server lives.
|
||||
pub(super) fn pulls_diagnostics_for(&self, uri: &str) -> bool {
|
||||
self.pull_diagnostics.is_some() && !self.has_published(uri)
|
||||
}
|
||||
|
||||
/// Ask for one document's diagnostics and cache the answer.
|
||||
///
|
||||
/// Best-effort: a refusal, or a server that sits on the request past `budget`, is logged and
|
||||
/// leaves the previous answer in place — the caller is a diagnostics read that still has a
|
||||
/// pushed cache to fall back on.
|
||||
pub(super) async fn pull_document_diagnostics(&mut self, uri: &str, budget: Duration) {
|
||||
let mut params = serde_json::json!({ "textDocument": { "uri": uri } });
|
||||
if let Some(identifier) = self.pull_diagnostics.as_ref().and_then(|p| p.identifier.clone())
|
||||
{
|
||||
params["identifier"] = Value::String(identifier);
|
||||
}
|
||||
if let Some(result_id) = self.pulled.get(uri).and_then(|report| report.result_id.clone()) {
|
||||
params["previousResultId"] = Value::String(result_id);
|
||||
}
|
||||
let request = self.send_request("textDocument/diagnostic", params);
|
||||
let response = match tokio::time::timeout(budget, request).await {
|
||||
Ok(Ok(response)) => response,
|
||||
Ok(Err(error)) => {
|
||||
debug!(uri, %error, "lsp: pull diagnostics refused");
|
||||
return;
|
||||
}
|
||||
Err(_) => {
|
||||
debug!(uri, ?budget, "lsp: pull diagnostics did not answer in the budget");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let result_id = response.get("resultId").and_then(Value::as_str).map(str::to_string);
|
||||
// `unchanged` means the previous answer still stands; only a `full` report carries items.
|
||||
if response.get("kind").and_then(Value::as_str) == Some("unchanged") {
|
||||
if let Some(report) = self.pulled.get_mut(uri) {
|
||||
report.result_id = result_id;
|
||||
}
|
||||
return;
|
||||
}
|
||||
let items = response
|
||||
.get("items")
|
||||
.and_then(Value::as_array)
|
||||
.map(|raw| {
|
||||
raw.iter()
|
||||
.filter_map(|item| match serde_json::from_value::<Diagnostic>(item.clone()) {
|
||||
Ok(diagnostic) => Some(diagnostic),
|
||||
Err(error) => {
|
||||
debug!(uri, %error, "lsp: dropping unparseable pulled diagnostic");
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
self.pulled.insert(uri.to_string(), PulledReport { result_id, items });
|
||||
}
|
||||
|
||||
/// Recent server-reported Error/Warning notices, formatted, newest last. Explains an empty
|
||||
/// diagnostics result when a server is misconfigured or can't drive its toolchain.
|
||||
pub fn server_notices(&self) -> Vec<String> {
|
||||
self.shared
|
||||
.inner
|
||||
.lock()
|
||||
.map(|inner| {
|
||||
inner
|
||||
.server_notices
|
||||
.iter()
|
||||
.map(|notice| {
|
||||
let label = if notice.severity == 1 { "error" } else { "warning" };
|
||||
format!("[{label}] {}", notice.text)
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
pub(super) fn cached_diagnostics(&self, uri: &str) -> Vec<Diagnostic> {
|
||||
let published = {
|
||||
let inner = self.shared.inner.lock().expect("diagnostics state poisoned");
|
||||
inner.diagnostics.get(uri).cloned()
|
||||
};
|
||||
published.unwrap_or_else(|| {
|
||||
self.pulled.get(uri).map(|report| report.items.clone()).unwrap_or_default()
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the server has published about this document, even to say it is clean.
|
||||
pub(super) fn has_published(&self, uri: &str) -> bool {
|
||||
self.shared.inner.lock().expect("diagnostics state poisoned").diagnostics.contains_key(uri)
|
||||
}
|
||||
|
||||
pub(super) fn publish_count(&self) -> u64 {
|
||||
self.shared.inner.lock().expect("diagnostics state poisoned").publish_count
|
||||
}
|
||||
}
|
||||
51
crates/luxe-lsp/src/client/error.rs
Normal file
51
crates/luxe-lsp/src/client/error.rs
Normal file
@@ -0,0 +1,51 @@
|
||||
//! Errors — what a language-server client can fail with.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::message::JsonRpcError;
|
||||
|
||||
/// LSP client errors.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum LspError {
|
||||
#[error("client not initialized")]
|
||||
NotInitialized,
|
||||
|
||||
#[error("failed to spawn language server '{server}': {error}")]
|
||||
SpawnFailed { server: String, error: String },
|
||||
|
||||
#[error("initialize timed out after {timeout:?} for server '{server}'")]
|
||||
InitTimeout { server: String, timeout: Duration },
|
||||
|
||||
/// The server was found and started, and then stopped before answering the handshake.
|
||||
///
|
||||
/// Distinct from [`Self::SpawnFailed`] (nothing to run) and [`Self::InitTimeout`] (running but
|
||||
/// silent), because it is the only one whose cause the *server* already explained — and the
|
||||
/// commonest way to reach it is a version-manager shim that resolves and then refuses.
|
||||
#[error("language server '{server}' exited during startup ({status}){}", detail(stderr))]
|
||||
ServerExited { server: String, status: String, stderr: String },
|
||||
|
||||
/// The server answered the request with a JSON-RPC error.
|
||||
///
|
||||
/// Its own words, propagated rather than flattened to an empty result — "no references found"
|
||||
/// and "this server cannot answer you" are not the same sentence.
|
||||
#[error("the language server refused the request: {} (code {})", .0.message, .0.code)]
|
||||
ServerRefused(JsonRpcError),
|
||||
|
||||
#[error("IO error: {0}")]
|
||||
IoError(#[from] std::io::Error),
|
||||
|
||||
#[error("serialization error: {0}")]
|
||||
Serialization(#[from] serde_json::Error),
|
||||
|
||||
#[error("request cancelled")]
|
||||
RequestCancelled,
|
||||
}
|
||||
|
||||
/// The server's own complaint, appended to an error when it made one.
|
||||
pub(super) fn detail(stderr: &str) -> String {
|
||||
let first: Vec<&str> = stderr.lines().filter(|line| !line.trim().is_empty()).take(3).collect();
|
||||
match first.is_empty() {
|
||||
true => String::new(),
|
||||
false => format!(": {}", first.join(" / ")),
|
||||
}
|
||||
}
|
||||
40
crates/luxe-lsp/src/client/language.rs
Normal file
40
crates/luxe-lsp/src/client/language.rs
Normal file
@@ -0,0 +1,40 @@
|
||||
//! Languages — which `languageId` a file's extension is opened under.
|
||||
|
||||
/// The LSP `languageId` for a document, by extension.
|
||||
///
|
||||
/// These are the identifiers the specification enumerates, not free-form names: `typescriptreact`
|
||||
/// for `.tsx`, `c` and `cpp` as separate languages, `csharp` rather than `cs`. A server is entitled
|
||||
/// to reject or mishandle one it does not know, and the wrong one is worse than a missing one
|
||||
/// because it asserts something false about the file.
|
||||
pub(super) fn language_id_for_extension(extension: &str) -> Option<&'static str> {
|
||||
Some(match extension {
|
||||
"rs" => "rust",
|
||||
"ts" | "mts" | "cts" => "typescript",
|
||||
"tsx" => "typescriptreact",
|
||||
"js" | "mjs" | "cjs" => "javascript",
|
||||
"jsx" => "javascriptreact",
|
||||
"py" | "pyi" => "python",
|
||||
"go" => "go",
|
||||
"c" => "c",
|
||||
"cc" | "cpp" | "cxx" | "c++" | "hh" | "hpp" | "hxx" => "cpp",
|
||||
"h" => "c",
|
||||
"java" => "java",
|
||||
"rb" => "ruby",
|
||||
"php" => "php",
|
||||
"cs" => "csharp",
|
||||
"swift" => "swift",
|
||||
"kt" | "kts" => "kotlin",
|
||||
"scala" | "sc" => "scala",
|
||||
"lua" => "lua",
|
||||
"zig" => "zig",
|
||||
"sh" | "bash" => "shellscript",
|
||||
"json" => "json",
|
||||
"jsonc" => "jsonc",
|
||||
"yaml" | "yml" => "yaml",
|
||||
"toml" => "toml",
|
||||
"md" | "markdown" => "markdown",
|
||||
"html" => "html",
|
||||
"css" => "css",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
300
crates/luxe-lsp/src/client/lifecycle.rs
Normal file
300
crates/luxe-lsp/src/client/lifecycle.rs
Normal file
@@ -0,0 +1,300 @@
|
||||
//! Lifecycle — starting a server, handshaking with it, and stopping it.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Keep the server's stderr drained for as long as it runs, retaining a bounded prefix.
|
||||
///
|
||||
/// Two jobs, and the second is the load-bearing one. The prefix is what a failed handshake
|
||||
/// reports. The *draining* is what keeps a talkative server alive: a pipe nobody reads fills at
|
||||
/// 64 KB and the next write blocks forever, so a server that narrates every request — clangd
|
||||
/// does, by default — wedges and then dies. Stopping the reader once the prefix is full and
|
||||
/// cancelling it once the handshake succeeds are the same bug twice.
|
||||
pub(super) fn drain_stderr(
|
||||
stderr: tokio::process::ChildStderr,
|
||||
) -> (tokio::task::JoinHandle<()>, Arc<Mutex<String>>) {
|
||||
/// Enough for a shim's refusal or a stack trace's first frames; a server that logs forever
|
||||
/// cannot grow this.
|
||||
const MAX: usize = 2_000;
|
||||
let collected = Arc::new(Mutex::new(String::new()));
|
||||
let sink = Arc::clone(&collected);
|
||||
let handle = tokio::spawn(async move {
|
||||
use tokio::io::AsyncReadExt;
|
||||
let mut reader = tokio::io::BufReader::new(stderr);
|
||||
let mut chunk = [0u8; 4096];
|
||||
let mut kept = Vec::new();
|
||||
while let Ok(read) = reader.read(&mut chunk).await {
|
||||
if read == 0 {
|
||||
break;
|
||||
}
|
||||
if kept.len() < MAX {
|
||||
let room = MAX - kept.len();
|
||||
kept.extend_from_slice(&chunk[..read.min(room)]);
|
||||
*sink.lock().await = String::from_utf8_lossy(&kept).trim().to_string();
|
||||
}
|
||||
// Past the prefix the bytes are dropped — but they are still read. See above.
|
||||
}
|
||||
});
|
||||
(handle, collected)
|
||||
}
|
||||
|
||||
/// Wait for the child to stop, rendering how it went.
|
||||
pub(super) async fn wait_for_exit(child: &mut tokio::process::Child) -> String {
|
||||
match child.wait().await {
|
||||
Ok(status) => status.to_string(),
|
||||
Err(error) => format!("could not be waited on: {error}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// How the `initialize` handshake ended, so the borrow of `self` can be released before reacting.
|
||||
pub(super) enum Handshake {
|
||||
/// The server answered.
|
||||
Answered(Result<serde_json::Value, LspError>),
|
||||
/// The server stopped first, rendered as its exit status.
|
||||
Exited(String),
|
||||
/// Neither happened inside the timeout.
|
||||
Silent,
|
||||
}
|
||||
|
||||
/// Reads a `diagnosticProvider` out of an `initialize` result.
|
||||
///
|
||||
/// The capability is either an options object or a registration object with an `id`; both carry the
|
||||
/// optional `identifier` a pull request has to echo back, and neither is a bare boolean.
|
||||
pub(super) fn pull_provider(init_response: &Value) -> Option<PullProvider> {
|
||||
let provider = init_response.get("capabilities")?.get("diagnosticProvider")?;
|
||||
provider.is_object().then(|| PullProvider {
|
||||
identifier: provider.get("identifier").and_then(Value::as_str).map(str::to_string),
|
||||
})
|
||||
}
|
||||
|
||||
/// How long a failed handshake waits for its server's exit status to become collectible.
|
||||
///
|
||||
/// Generous next to the gap it covers (a process that has already closed its pipes is reaped in
|
||||
/// microseconds, milliseconds on a loaded machine) and short enough to be invisible on the only
|
||||
/// other path that reaches it — a live server that refused the handshake for some other reason.
|
||||
pub(super) const EXIT_GRACE: Duration = Duration::from_millis(250);
|
||||
|
||||
/// How long a server gets to exit after `shutdown` and `exit` before it is killed.
|
||||
pub(super) const SHUTDOWN_GRACE: Duration = Duration::from_secs(2);
|
||||
|
||||
/// What the client tells a server about itself.
|
||||
///
|
||||
/// Advertises progress and diagnostics, so a server streams `$/progress` and `publishDiagnostics`.
|
||||
///
|
||||
/// And `codeAction`, which is not optional politeness: a server answers `textDocument/codeAction`
|
||||
/// with an empty list unless the client says it understands code action *literals*, because the
|
||||
/// older reply shape is a `Command` it cannot assume we can run. Undeclared, rust-analyzer answers
|
||||
/// every `lsp_navigation action=code_action` with nothing. `resolveSupport` is the other half: an
|
||||
/// action whose `edit` is computed lazily arrives without one, and applying it means asking for it.
|
||||
fn initialize_params(root: &std::path::Path) -> Value {
|
||||
serde_json::json!({
|
||||
"processId": std::process::id(),
|
||||
"rootUri": crate::uri::from_path(root),
|
||||
"capabilities": {
|
||||
"window": { "workDoneProgress": true },
|
||||
"textDocument": {
|
||||
"synchronization": { "didSave": true, "dynamicRegistration": false },
|
||||
"publishDiagnostics": { "relatedInformation": true },
|
||||
// The pull half of diagnostics. A server only advertises
|
||||
// `diagnosticProvider` when the client says it can ask, and one that answers
|
||||
// *only* this way — TypeScript 7's native LSP — pushes nothing for an open
|
||||
// file, so without this its errors are invisible and read as "clean".
|
||||
// `relatedDocumentSupport: false` keeps an answer to one file about that file.
|
||||
"diagnostic": {
|
||||
"dynamicRegistration": false,
|
||||
"relatedDocumentSupport": false
|
||||
},
|
||||
"codeAction": {
|
||||
"dataSupport": true,
|
||||
"resolveSupport": { "properties": ["edit"] },
|
||||
"codeActionLiteralSupport": {
|
||||
"codeActionKind": {
|
||||
"valueSet": [
|
||||
"", "quickfix", "refactor", "refactor.extract",
|
||||
"refactor.inline", "refactor.rewrite", "source",
|
||||
"source.organizeImports", "source.fixAll"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
// rust-analyzer signals readiness via this experimental notification.
|
||||
"experimental": { "serverStatusNotification": true }
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// A server's stderr drain: the task, and what it has kept.
|
||||
type Complaints = (tokio::task::JoinHandle<()>, Arc<Mutex<String>>);
|
||||
|
||||
impl LspClient {
|
||||
/// Initialize the language server: spawn the process and perform the LSP handshake.
|
||||
pub async fn initialize(&mut self) -> Result<(), LspError> {
|
||||
let (mut child, complaints) = self.spawn_server()?;
|
||||
let outcome = self.race_handshake(&mut child).await;
|
||||
self.child = Some(child);
|
||||
let init_response = self.handshake_result(outcome, complaints).await?;
|
||||
debug!("LSP server initialized: {init_response:?}");
|
||||
self.pull_diagnostics = pull_provider(&init_response);
|
||||
|
||||
self.notify("initialized", serde_json::json!({})).await?;
|
||||
// Ready only now: a client whose handshake failed must not report that it can be asked.
|
||||
self.state = ClientState::Initialized;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Starts the server process and the reader that routes what it says, and keeps its stderr.
|
||||
fn spawn_server(&mut self) -> Result<(Child, Option<Complaints>), LspError> {
|
||||
let mut cmd = Command::new(&self.config.command[0]);
|
||||
cmd.args(&self.config.command[1..]);
|
||||
cmd.current_dir(&self.config.root_path);
|
||||
cmd.stdin(std::process::Stdio::piped());
|
||||
cmd.stdout(std::process::Stdio::piped());
|
||||
// Piped, not null: when a server refuses to start it says why here, and that sentence is
|
||||
// the whole answer. Discarded, every startup failure would look like a timeout.
|
||||
cmd.stderr(std::process::Stdio::piped());
|
||||
cmd.kill_on_drop(true);
|
||||
|
||||
let mut child = cmd.spawn().map_err(|e| LspError::SpawnFailed {
|
||||
server: self.config.server_id.clone(),
|
||||
error: e.to_string(),
|
||||
})?;
|
||||
|
||||
let stdin = child
|
||||
.stdin
|
||||
.take()
|
||||
.ok_or_else(|| LspError::IoError(std::io::Error::other("Failed to take stdin")))?;
|
||||
let stdout = child
|
||||
.stdout
|
||||
.take()
|
||||
.ok_or_else(|| LspError::IoError(std::io::Error::other("Failed to take stdout")))?;
|
||||
let complaints = child.stderr.take().map(drain_stderr);
|
||||
let stdin = Arc::new(Mutex::new(stdin));
|
||||
self.stdin = Some(stdin.clone());
|
||||
|
||||
// Background reader must run before the initialize request so the response is routed.
|
||||
let tx = self.notification_tx.clone();
|
||||
let pending = self.pending_requests.clone();
|
||||
let shared = self.shared.clone();
|
||||
let mut stdout = tokio::io::BufReader::new(stdout);
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = read_loop(&mut stdout, shared, stdin, tx, pending).await {
|
||||
error!("LSP reader task exited with error: {e}");
|
||||
}
|
||||
});
|
||||
Ok((child, complaints))
|
||||
}
|
||||
|
||||
/// Sends `initialize` and waits for whichever comes first: the answer, the server stopping, or
|
||||
/// the timeout.
|
||||
async fn race_handshake(&mut self, child: &mut Child) -> Handshake {
|
||||
let init_params = initialize_params(&self.config.root_path);
|
||||
let init_timeout = self.config.init_timeout;
|
||||
// Race the handshake against the server *stopping*. A server that dies in ten milliseconds
|
||||
// — a shim with no version set, a missing runtime, a bad config — is not the same as one
|
||||
// that is merely slow, and waiting out the whole timeout would tell the caller the wrong
|
||||
// thing. Whichever finishes first is the answer.
|
||||
let mut outcome = {
|
||||
let handshake = self.request("initialize", init_params);
|
||||
tokio::pin!(handshake);
|
||||
tokio::select! {
|
||||
biased;
|
||||
response = &mut handshake => Handshake::Answered(response),
|
||||
status = wait_for_exit(child) => Handshake::Exited(status),
|
||||
() = tokio::time::sleep(init_timeout) => Handshake::Silent,
|
||||
}
|
||||
};
|
||||
// A server can lose the race with its own pipes: die fast enough and the *write* fails
|
||||
// before the exit is observable, leaving a bare "Broken pipe". A handshake that
|
||||
// never got an answer, against a process that has since exited, *is* that exit — and the
|
||||
// exit is the useful half.
|
||||
//
|
||||
// Waited for rather than polled once. The kernel delivers `EPIPE` the moment the read end
|
||||
// closes, but the exit *status* only becomes collectible when this process is notified,
|
||||
// which under load lands later — so a single `try_wait` answers "still running" about a
|
||||
// process that is already gone and the caller is told about a broken pipe instead. Bounded,
|
||||
// because a live server that refused for some other reason must not be waited on for long.
|
||||
if matches!(
|
||||
&outcome,
|
||||
Handshake::Answered(Err(LspError::IoError(_) | LspError::RequestCancelled))
|
||||
) {
|
||||
if let Ok(status) = timeout(EXIT_GRACE, wait_for_exit(child)).await {
|
||||
outcome = Handshake::Exited(status);
|
||||
}
|
||||
}
|
||||
outcome
|
||||
}
|
||||
|
||||
/// The answer to `initialize`, or why there is none: the server's exit with what it said, or
|
||||
/// the silence.
|
||||
async fn handshake_result(
|
||||
&mut self,
|
||||
outcome: Handshake,
|
||||
complaints: Option<Complaints>,
|
||||
) -> Result<Value, LspError> {
|
||||
let server_id = self.config.server_id.clone();
|
||||
let init_timeout = self.config.init_timeout;
|
||||
let init_response = match outcome {
|
||||
Handshake::Exited(status) => {
|
||||
let stderr = match complaints {
|
||||
Some((handle, buffer)) => {
|
||||
// The child is gone, so its stderr is at EOF and the drain ends on its own.
|
||||
let _ = handle.await;
|
||||
buffer.lock().await.clone()
|
||||
}
|
||||
None => String::new(),
|
||||
};
|
||||
return Err(LspError::ServerExited { server: server_id, status, stderr });
|
||||
}
|
||||
// The drain runs for the life of the server, and the handle is held so shutdown can end
|
||||
// it. Cancelling it here instead, to avoid detaching a `JoinHandle`, wedges any server
|
||||
// that logs more than a pipe buffer: clangd narrates every request to stderr by
|
||||
// default, fills 64 KB during its first index, and blocks forever on the next write.
|
||||
other => {
|
||||
if let Some((handle, _)) = complaints {
|
||||
self.stderr_drain = Some(handle);
|
||||
}
|
||||
match other {
|
||||
Handshake::Answered(response) => response?,
|
||||
Handshake::Silent => {
|
||||
return Err(LspError::InitTimeout {
|
||||
server: server_id,
|
||||
timeout: init_timeout,
|
||||
})
|
||||
}
|
||||
Handshake::Exited(_) => unreachable!("handled above"),
|
||||
}
|
||||
}
|
||||
};
|
||||
Ok(init_response)
|
||||
}
|
||||
|
||||
/// Shut the server down cleanly, sending `shutdown` + `exit` and reaping the child.
|
||||
pub async fn shutdown(&mut self) -> Result<(), LspError> {
|
||||
if self.state == ClientState::Shutdown {
|
||||
return Ok(());
|
||||
}
|
||||
if let Some(stdin) = self.stdin.clone() {
|
||||
let mut guard = stdin.lock().await;
|
||||
for message in [
|
||||
JsonRpcMessage::request(0, "shutdown".to_string(), serde_json::json!({})),
|
||||
JsonRpcMessage::notification("exit".to_string(), serde_json::json!({})),
|
||||
] {
|
||||
if let Ok(json) = serde_json::to_string(&message) {
|
||||
let _ = write_frame(&mut *guard, json.as_bytes()).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(handle) = self.stderr_drain.take() {
|
||||
handle.abort();
|
||||
}
|
||||
if let Some(mut child) = self.child.take() {
|
||||
// a server that ignores `exit` must not hold its caller forever
|
||||
if timeout(SHUTDOWN_GRACE, child.wait()).await.is_err() {
|
||||
let _ = child.start_kill();
|
||||
let _ = child.wait().await;
|
||||
}
|
||||
}
|
||||
self.state = ClientState::Shutdown;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
423
crates/luxe-lsp/src/client/nav.rs
Normal file
423
crates/luxe-lsp/src/client/nav.rs
Normal file
@@ -0,0 +1,423 @@
|
||||
//! LSP navigation requests — definition, references, symbols, hover, call hierarchy, and more.
|
||||
//!
|
||||
//! Responses are parsed **leniently**: real servers return `LocationLink[]` for definition and
|
||||
//! hierarchical `DocumentSymbol[]` for document symbols, not just the simplest shapes, so the
|
||||
//! helpers here normalize both. Complex results (signature help, call hierarchy, code actions,
|
||||
//! rename edits) are returned as raw `Value` for the tool layer to format.
|
||||
|
||||
use super::*;
|
||||
use crate::protocol::FlatSymbol;
|
||||
|
||||
impl LspClient {
|
||||
/// Go to definition; returns the first resolved location.
|
||||
pub async fn goto_definition(
|
||||
&mut self,
|
||||
uri: &str,
|
||||
position: Position,
|
||||
) -> Result<Option<Location>, LspError> {
|
||||
let result = self.position_request("textDocument/definition", uri, position).await?;
|
||||
Ok(parse_locations(&result).into_iter().next())
|
||||
}
|
||||
|
||||
/// Go to the type definition of the symbol at a position.
|
||||
pub async fn goto_type_definition(
|
||||
&mut self,
|
||||
uri: &str,
|
||||
position: Position,
|
||||
) -> Result<Vec<Location>, LspError> {
|
||||
let result = self.position_request("textDocument/typeDefinition", uri, position).await?;
|
||||
Ok(parse_locations(&result))
|
||||
}
|
||||
|
||||
/// Go to the declaration of the symbol at a position.
|
||||
pub async fn goto_declaration(
|
||||
&mut self,
|
||||
uri: &str,
|
||||
position: Position,
|
||||
) -> Result<Vec<Location>, LspError> {
|
||||
let result = self.position_request("textDocument/declaration", uri, position).await?;
|
||||
Ok(parse_locations(&result))
|
||||
}
|
||||
|
||||
/// Find implementations of the symbol at a position.
|
||||
pub async fn goto_implementation(
|
||||
&mut self,
|
||||
uri: &str,
|
||||
position: Position,
|
||||
) -> Result<Vec<Location>, LspError> {
|
||||
let result = self.position_request("textDocument/implementation", uri, position).await?;
|
||||
Ok(parse_locations(&result))
|
||||
}
|
||||
|
||||
/// Find all references to a symbol.
|
||||
pub async fn find_references(
|
||||
&mut self,
|
||||
uri: &str,
|
||||
position: Position,
|
||||
) -> Result<Vec<Location>, LspError> {
|
||||
let result = self
|
||||
.send_request(
|
||||
"textDocument/references",
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"position": { "line": position.line, "character": position.character },
|
||||
"context": { "includeDeclaration": false }
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
Ok(parse_locations(&result))
|
||||
}
|
||||
|
||||
/// List the symbols in a document (flattened; handles both server shapes).
|
||||
pub async fn document_symbols(&mut self, uri: &str) -> Result<Vec<FlatSymbol>, LspError> {
|
||||
let result = self
|
||||
.send_request(
|
||||
"textDocument/documentSymbol",
|
||||
serde_json::json!({ "textDocument": { "uri": uri } }),
|
||||
)
|
||||
.await?;
|
||||
let mut symbols = Vec::new();
|
||||
flatten_symbols(&result, uri, None, &mut symbols);
|
||||
Ok(symbols)
|
||||
}
|
||||
|
||||
/// Search for symbols across the workspace by name.
|
||||
pub async fn workspace_symbol(&mut self, query: &str) -> Result<Vec<FlatSymbol>, LspError> {
|
||||
let result =
|
||||
self.send_request("workspace/symbol", serde_json::json!({ "query": query })).await?;
|
||||
let mut symbols = Vec::new();
|
||||
flatten_symbols(&result, "", None, &mut symbols);
|
||||
Ok(symbols)
|
||||
}
|
||||
|
||||
/// Get hover information for a symbol at a position.
|
||||
pub async fn hover(
|
||||
&mut self,
|
||||
uri: &str,
|
||||
position: Position,
|
||||
) -> Result<Option<MarkupContent>, LspError> {
|
||||
let result = self.position_request("textDocument/hover", uri, position).await?;
|
||||
if let Value::Object(obj) = &result {
|
||||
if let Some(contents) = obj.get("contents") {
|
||||
// `contents` may be MarkupContent, a MarkedString, or an array of them.
|
||||
if let Ok(markup) = serde_json::from_value::<MarkupContent>(contents.clone()) {
|
||||
return Ok(Some(markup));
|
||||
}
|
||||
if let Some(text) = hover_plain_text(contents) {
|
||||
return Ok(Some(MarkupContent { kind: "plaintext".to_string(), value: text }));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// Get signature help at a call-site position (raw result).
|
||||
pub async fn signature_help(
|
||||
&mut self,
|
||||
uri: &str,
|
||||
position: Position,
|
||||
) -> Result<Value, LspError> {
|
||||
self.position_request("textDocument/signatureHelp", uri, position).await
|
||||
}
|
||||
|
||||
/// Prepare a call hierarchy at a position; returns raw `CallHierarchyItem`s.
|
||||
pub async fn prepare_call_hierarchy(
|
||||
&mut self,
|
||||
uri: &str,
|
||||
position: Position,
|
||||
) -> Result<Vec<Value>, LspError> {
|
||||
let result =
|
||||
self.position_request("textDocument/prepareCallHierarchy", uri, position).await?;
|
||||
Ok(as_array(result))
|
||||
}
|
||||
|
||||
/// Fetch incoming calls for a prepared call-hierarchy item.
|
||||
pub async fn incoming_calls(&mut self, item: Value) -> Result<Vec<Value>, LspError> {
|
||||
let result = self
|
||||
.send_request("callHierarchy/incomingCalls", serde_json::json!({ "item": item }))
|
||||
.await?;
|
||||
Ok(as_array(result))
|
||||
}
|
||||
|
||||
/// Fetch outgoing calls for a prepared call-hierarchy item.
|
||||
pub async fn outgoing_calls(&mut self, item: Value) -> Result<Vec<Value>, LspError> {
|
||||
let result = self
|
||||
.send_request("callHierarchy/outgoingCalls", serde_json::json!({ "item": item }))
|
||||
.await?;
|
||||
Ok(as_array(result))
|
||||
}
|
||||
|
||||
/// List code actions (quick fixes/refactors) for a range (raw results).
|
||||
pub async fn code_action(
|
||||
&mut self,
|
||||
uri: &str,
|
||||
range: crate::protocol::Range,
|
||||
) -> Result<Vec<Value>, LspError> {
|
||||
// The diagnostics overlapping `range`, not an empty list. The spec is explicit that this is
|
||||
// how a server learns "which errors are currently presented to the user for the given
|
||||
// range", and a quickfix is offered *for a diagnostic* — so a client that sends none is
|
||||
// asking for refactors and opting out of every fix. We already hold these; sending them
|
||||
// costs a filter.
|
||||
let overlapping = self.diagnostics_overlapping(uri, &range);
|
||||
let result = self
|
||||
.send_request(
|
||||
"textDocument/codeAction",
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"range": range,
|
||||
"context": { "diagnostics": overlapping }
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
Ok(as_array(result))
|
||||
}
|
||||
|
||||
/// This document's cached diagnostics whose range overlaps `range`.
|
||||
///
|
||||
/// Line granularity, deliberately: a caller points at a line, and a diagnostic that starts
|
||||
/// mid-line would be missed by a strict character comparison against a zero-width position.
|
||||
fn diagnostics_overlapping(
|
||||
&self,
|
||||
uri: &str,
|
||||
range: &crate::protocol::Range,
|
||||
) -> Vec<serde_json::Value> {
|
||||
let Ok(state) = self.shared.inner.lock() else { return Vec::new() };
|
||||
state
|
||||
.diagnostics
|
||||
.get(uri)
|
||||
.map(|diagnostics| {
|
||||
diagnostics
|
||||
.iter()
|
||||
.filter(|diagnostic| {
|
||||
diagnostic.range.start.line <= range.end.line
|
||||
&& diagnostic.range.end.line >= range.start.line
|
||||
})
|
||||
.filter_map(|diagnostic| serde_json::to_value(diagnostic).ok())
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Compute a rename edit (raw `WorkspaceEdit`); the caller previews or applies it.
|
||||
pub async fn rename(
|
||||
&mut self,
|
||||
uri: &str,
|
||||
position: Position,
|
||||
new_name: &str,
|
||||
) -> Result<Value, LspError> {
|
||||
self.send_request(
|
||||
"textDocument/rename",
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"position": { "line": position.line, "character": position.character },
|
||||
"newName": new_name
|
||||
}),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Shared `{ textDocument, position }` request.
|
||||
async fn position_request(
|
||||
&mut self,
|
||||
method: &str,
|
||||
uri: &str,
|
||||
position: Position,
|
||||
) -> Result<Value, LspError> {
|
||||
self.send_request(
|
||||
method,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"position": { "line": position.line, "character": position.character }
|
||||
}),
|
||||
)
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
/// Coerce a result into an array of values (single object → one-element vec).
|
||||
fn as_array(result: Value) -> Vec<Value> {
|
||||
match result {
|
||||
Value::Array(items) => items,
|
||||
Value::Null => Vec::new(),
|
||||
other => vec![other],
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse a definition-style result into `Location`s, accepting `Location`, `Location[]`, or
|
||||
/// `LocationLink[]` (target-based, as rust-analyzer/tsserver return).
|
||||
fn parse_locations(result: &Value) -> Vec<Location> {
|
||||
match result {
|
||||
Value::Array(items) => items.iter().filter_map(parse_location).collect(),
|
||||
Value::Object(_) => parse_location(result).into_iter().collect(),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse one `Location` or `LocationLink` leniently.
|
||||
fn parse_location(value: &Value) -> Option<Location> {
|
||||
if let Ok(location) = serde_json::from_value::<Location>(value.clone()) {
|
||||
return Some(location);
|
||||
}
|
||||
// LocationLink: `targetUri` + `targetSelectionRange`/`targetRange`.
|
||||
let uri = value.get("targetUri")?.as_str()?.to_string();
|
||||
let range = value
|
||||
.get("targetSelectionRange")
|
||||
.or_else(|| value.get("targetRange"))
|
||||
.and_then(|r| serde_json::from_value::<crate::protocol::Range>(r.clone()).ok())?;
|
||||
Some(Location { uri, range })
|
||||
}
|
||||
|
||||
/// Flatten a `documentSymbol`/`workspace/symbol` result into [`FlatSymbol`]s, handling both
|
||||
/// `SymbolInformation` (flat, has `location`) and `DocumentSymbol` (nested, has `selectionRange` +
|
||||
/// `children`).
|
||||
fn flatten_symbols(
|
||||
value: &Value,
|
||||
default_uri: &str,
|
||||
container: Option<&str>,
|
||||
out: &mut Vec<FlatSymbol>,
|
||||
) {
|
||||
let Value::Array(items) = value else { return };
|
||||
for item in items {
|
||||
let name = item.get("name").and_then(Value::as_str).unwrap_or("").to_string();
|
||||
let kind = item.get("kind").and_then(Value::as_u64).unwrap_or(0) as u32;
|
||||
|
||||
if let Some(location) = item.get("location") {
|
||||
// SymbolInformation / WorkspaceSymbol: `location.range` is the full extent, and there
|
||||
// is no separate selection range.
|
||||
let uri =
|
||||
location.get("uri").and_then(Value::as_str).unwrap_or(default_uri).to_string();
|
||||
let (line, character) = range_start(location.get("range"));
|
||||
let (start_line, end_line) = range_span(location.get("range"));
|
||||
let container = item
|
||||
.get("containerName")
|
||||
.and_then(Value::as_str)
|
||||
.map(str::to_string)
|
||||
.or_else(|| container.map(str::to_string));
|
||||
out.push(FlatSymbol {
|
||||
name,
|
||||
kind,
|
||||
uri,
|
||||
line,
|
||||
character,
|
||||
start_line,
|
||||
end_line,
|
||||
container,
|
||||
});
|
||||
} else if item.get("selectionRange").is_some() || item.get("range").is_some() {
|
||||
// DocumentSymbol (hierarchical): `selectionRange` names it, `range` is its body.
|
||||
let (line, character) =
|
||||
range_start(item.get("selectionRange").or_else(|| item.get("range")));
|
||||
let (start_line, end_line) =
|
||||
range_span(item.get("range").or_else(|| item.get("selectionRange")));
|
||||
out.push(FlatSymbol {
|
||||
name: name.clone(),
|
||||
kind,
|
||||
uri: default_uri.to_string(),
|
||||
line,
|
||||
character,
|
||||
start_line,
|
||||
end_line,
|
||||
container: container.map(str::to_string),
|
||||
});
|
||||
if let Some(children) = item.get("children") {
|
||||
flatten_symbols(children, default_uri, Some(&name), out);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Extract a range's 0-based `(line, character)` start, defaulting to `(0, 0)`.
|
||||
fn range_start(range: Option<&Value>) -> (u32, u32) {
|
||||
let start = range.and_then(|r| r.get("start"));
|
||||
let line = start.and_then(|s| s.get("line")).and_then(Value::as_u64).unwrap_or(0) as u32;
|
||||
let character =
|
||||
start.and_then(|s| s.get("character")).and_then(Value::as_u64).unwrap_or(0) as u32;
|
||||
(line, character)
|
||||
}
|
||||
|
||||
/// Extract a range's 0-based `(start_line, end_line)`, defaulting the end to the start.
|
||||
fn range_span(range: Option<&Value>) -> (u32, u32) {
|
||||
let line_of = |key: &str| {
|
||||
range
|
||||
.and_then(|r| r.get(key))
|
||||
.and_then(|p| p.get("line"))
|
||||
.and_then(Value::as_u64)
|
||||
.unwrap_or(0) as u32
|
||||
};
|
||||
let start = line_of("start");
|
||||
(start, line_of("end").max(start))
|
||||
}
|
||||
|
||||
/// Best-effort plain text from a hover `contents` that is a `MarkedString` or an array of them.
|
||||
fn hover_plain_text(contents: &Value) -> Option<String> {
|
||||
match contents {
|
||||
Value::String(s) => Some(s.clone()),
|
||||
Value::Object(obj) => obj.get("value").and_then(Value::as_str).map(str::to_string),
|
||||
Value::Array(items) => {
|
||||
let joined = items.iter().filter_map(hover_plain_text).collect::<Vec<_>>().join("\n");
|
||||
(!joined.is_empty()).then_some(joined)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parse_locations_accepts_location_and_location_link() {
|
||||
let plain = serde_json::json!([{
|
||||
"uri": "file:///a.rs",
|
||||
"range": { "start": { "line": 3, "character": 2 }, "end": { "line": 3, "character": 8 } }
|
||||
}]);
|
||||
let link = serde_json::json!([{
|
||||
"targetUri": "file:///b.rs",
|
||||
"targetSelectionRange": {
|
||||
"start": { "line": 10, "character": 4 }, "end": { "line": 10, "character": 9 }
|
||||
},
|
||||
"targetRange": {
|
||||
"start": { "line": 9, "character": 0 }, "end": { "line": 12, "character": 1 }
|
||||
}
|
||||
}]);
|
||||
assert_eq!(parse_locations(&plain)[0].uri, "file:///a.rs");
|
||||
let linked = parse_locations(&link);
|
||||
assert_eq!(linked[0].uri, "file:///b.rs");
|
||||
assert_eq!(linked[0].range.start.line, 10);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flatten_handles_both_symbol_shapes() {
|
||||
// SymbolInformation
|
||||
let flat = serde_json::json!([{
|
||||
"name": "main", "kind": 12,
|
||||
"location": { "uri": "file:///m.rs",
|
||||
"range": { "start": { "line": 1, "character": 0 }, "end": { "line": 1, "character": 4 } } },
|
||||
"containerName": "app"
|
||||
}]);
|
||||
let mut out = Vec::new();
|
||||
flatten_symbols(&flat, "file:///m.rs", None, &mut out);
|
||||
assert_eq!(out[0].name, "main");
|
||||
assert_eq!(out[0].line, 1);
|
||||
assert_eq!(out[0].container.as_deref(), Some("app"));
|
||||
|
||||
// DocumentSymbol (nested), children inherit the parent as container.
|
||||
let nested = serde_json::json!([{
|
||||
"name": "Foo", "kind": 23,
|
||||
"range": { "start": { "line": 0, "character": 0 }, "end": { "line": 9, "character": 0 } },
|
||||
"selectionRange": { "start": { "line": 0, "character": 7 }, "end": { "line": 0, "character": 10 } },
|
||||
"children": [{
|
||||
"name": "bar", "kind": 6,
|
||||
"range": { "start": { "line": 2, "character": 4 }, "end": { "line": 4, "character": 5 } },
|
||||
"selectionRange": { "start": { "line": 2, "character": 7 }, "end": { "line": 2, "character": 10 } }
|
||||
}]
|
||||
}]);
|
||||
let mut out = Vec::new();
|
||||
flatten_symbols(&nested, "file:///t.rs", None, &mut out);
|
||||
assert_eq!(out.len(), 2);
|
||||
assert_eq!(out[0].name, "Foo");
|
||||
assert_eq!(out[0].character, 7);
|
||||
assert_eq!(out[1].name, "bar");
|
||||
assert_eq!(out[1].container.as_deref(), Some("Foo"));
|
||||
}
|
||||
}
|
||||
138
crates/luxe-lsp/src/client/state.rs
Normal file
138
crates/luxe-lsp/src/client/state.rs
Normal file
@@ -0,0 +1,138 @@
|
||||
//! Client state — what the background reader folds in, and the requests waiting on it.
|
||||
|
||||
use crate::message::JsonRpcError;
|
||||
use crate::protocol::Diagnostic;
|
||||
use serde_json::Value;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex as SyncMutex};
|
||||
use std::time::{Duration, Instant};
|
||||
use tokio::sync::{oneshot, Mutex, Notify};
|
||||
|
||||
/// Live server→client state folded by the background reader.
|
||||
///
|
||||
/// Guarded by a std mutex held only for brief, non-async updates: the diagnostics cache keyed by
|
||||
/// document URI, a count of in-flight `$/progress` work-done tokens, a monotonic publish counter,
|
||||
/// and the last-change instant used for quiescence.
|
||||
pub(crate) struct DiagnosticsState {
|
||||
/// Latest *published* diagnostics per document URI.
|
||||
///
|
||||
/// The key is itself an answer: present with an empty vec means the server said "clean", and
|
||||
/// absent means it has said nothing at all, which is what decides whether a pull-capable
|
||||
/// server still has to be asked directly. Only `publishDiagnostics` writes here — a pulled
|
||||
/// report lives on the client, in [`LspClient::pulled`], so the distinction survives.
|
||||
pub(crate) diagnostics: HashMap<String, Vec<Diagnostic>>,
|
||||
/// In-flight work-done progress tokens; `0` means the server is idle.
|
||||
pub(crate) progress_active: usize,
|
||||
/// Monotonic count of `publishDiagnostics` notifications seen.
|
||||
pub(crate) publish_count: u64,
|
||||
/// Whether the server reported itself quiescent (ready) via `experimental/serverStatus` — the
|
||||
/// reliable readiness signal for rust-analyzer. Other servers leave this `false` and readiness
|
||||
/// falls back to a progress-settle window.
|
||||
pub(crate) quiescent: bool,
|
||||
/// Recent server-reported Error/Warning notices (`window/showMessage` + `window/logMessage`),
|
||||
/// bounded. Surfaced when a diagnostics read comes back empty so a broken/misconfigured server
|
||||
/// (e.g. it can't find a usable toolchain) isn't a silent "no diagnostics".
|
||||
pub(crate) server_notices: Vec<ServerNotice>,
|
||||
/// Instant of the last diagnostics/progress change, for quiescence checks.
|
||||
last_change: Instant,
|
||||
}
|
||||
|
||||
/// One Error/Warning message a server sent via `window/showMessage` or `window/logMessage`.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct ServerNotice {
|
||||
/// LSP `MessageType`: 1 = Error, 2 = Warning.
|
||||
pub(crate) severity: u8,
|
||||
pub(crate) text: String,
|
||||
}
|
||||
|
||||
/// A server's advertised `diagnosticProvider`, as far as a pull request needs it.
|
||||
#[derive(Debug)]
|
||||
pub(super) struct PullProvider {
|
||||
/// The identifier the server registered under, echoed back on every request it asked for.
|
||||
pub(super) identifier: Option<String>,
|
||||
}
|
||||
|
||||
/// The last `textDocument/diagnostic` answer for one document.
|
||||
#[derive(Debug)]
|
||||
pub(super) struct PulledReport {
|
||||
/// The server's token for this answer, sent back so it can reply `unchanged`.
|
||||
pub(super) result_id: Option<String>,
|
||||
pub(super) items: Vec<Diagnostic>,
|
||||
}
|
||||
|
||||
impl DiagnosticsState {
|
||||
pub(crate) fn mark_change(&mut self) {
|
||||
self.last_change = Instant::now();
|
||||
}
|
||||
|
||||
/// Record a server Error/Warning notice (deduping the immediately-repeated one, bounded).
|
||||
pub(crate) fn push_notice(&mut self, severity: u8, text: String) {
|
||||
if self.server_notices.last().is_some_and(|n| n.text == text) {
|
||||
return;
|
||||
}
|
||||
self.server_notices.push(ServerNotice { severity, text });
|
||||
const MAX_NOTICES: usize = 8;
|
||||
let len = self.server_notices.len();
|
||||
if len > MAX_NOTICES {
|
||||
self.server_notices.drain(0..len - MAX_NOTICES);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn since_change(&self) -> Duration {
|
||||
self.last_change.elapsed()
|
||||
}
|
||||
}
|
||||
|
||||
/// In-flight requests, each waiting on the server's answer or its refusal.
|
||||
pub(crate) type PendingRequests =
|
||||
Arc<Mutex<HashMap<u64, oneshot::Sender<Result<Value, JsonRpcError>>>>>;
|
||||
|
||||
/// Removes a request's pending entry however the request ends.
|
||||
pub(super) struct PendingEntry {
|
||||
pub(super) pending: PendingRequests,
|
||||
pub(super) id: u64,
|
||||
}
|
||||
|
||||
impl Drop for PendingEntry {
|
||||
fn drop(&mut self) {
|
||||
let id = self.id;
|
||||
if let Ok(mut map) = self.pending.try_lock() {
|
||||
map.remove(&id);
|
||||
return;
|
||||
}
|
||||
// the reader holds it for a moment; finish the removal behind it
|
||||
let pending = Arc::clone(&self.pending);
|
||||
if let Ok(runtime) = tokio::runtime::Handle::try_current() {
|
||||
runtime.spawn(async move { pending.lock().await.remove(&id) });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Shared state between the client and its background reader.
|
||||
pub(crate) struct SharedState {
|
||||
pub(crate) inner: SyncMutex<DiagnosticsState>,
|
||||
pub(crate) notify: Notify,
|
||||
}
|
||||
|
||||
impl SharedState {
|
||||
pub(super) fn new() -> Arc<Self> {
|
||||
Arc::new(Self {
|
||||
inner: SyncMutex::new(DiagnosticsState {
|
||||
diagnostics: HashMap::new(),
|
||||
progress_active: 0,
|
||||
publish_count: 0,
|
||||
quiescent: false,
|
||||
server_notices: Vec::new(),
|
||||
last_change: Instant::now(),
|
||||
}),
|
||||
notify: Notify::new(),
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn mark_change(&self) {
|
||||
if let Ok(mut inner) = self.inner.lock() {
|
||||
inner.mark_change();
|
||||
}
|
||||
self.notify.notify_waiters();
|
||||
}
|
||||
}
|
||||
218
crates/luxe-lsp/src/client/tests.rs
Normal file
218
crates/luxe-lsp/src/client/tests.rs
Normal file
@@ -0,0 +1,218 @@
|
||||
use super::diagnostics::hash_content;
|
||||
use super::lifecycle::pull_provider;
|
||||
use super::*;
|
||||
use crate::protocol::Range;
|
||||
|
||||
fn config() -> LspConfig {
|
||||
LspConfig {
|
||||
command: vec!["rust-analyzer".to_string()],
|
||||
server_id: "rust-analyzer".to_string(),
|
||||
root_path: PathBuf::from("/tmp"),
|
||||
init_timeout: Duration::from_secs(30),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_shutdown_when_not_initialized() {
|
||||
let mut client = LspClient::new(config());
|
||||
assert_eq!(client.state, ClientState::Uninitialized);
|
||||
client.shutdown().await.unwrap();
|
||||
assert_eq!(client.state, ClientState::Shutdown);
|
||||
}
|
||||
|
||||
/// The spec enumerates these identifiers; a wrong one asserts something false about the file.
|
||||
#[test]
|
||||
fn language_id_is_inferred_from_the_uri_extension() {
|
||||
let client = |language: &str| {
|
||||
LspClient::new(LspConfig {
|
||||
command: vec!["true".to_string()],
|
||||
server_id: language.to_string(),
|
||||
root_path: PathBuf::from("/tmp"),
|
||||
init_timeout: Duration::from_secs(1),
|
||||
})
|
||||
};
|
||||
let rust = client("rust");
|
||||
assert_eq!(rust.language_id_for("file:///a/b.rs"), "rust");
|
||||
assert_eq!(rust.language_id_for("file:///a/b.ts"), "typescript");
|
||||
assert_eq!(rust.language_id_for("file:///a/b.py"), "python");
|
||||
assert_eq!(rust.language_id_for("file:///a/b.go"), "go");
|
||||
// React variants are their own languages, not the plain ones.
|
||||
assert_eq!(rust.language_id_for("file:///a/b.tsx"), "typescriptreact");
|
||||
assert_eq!(rust.language_id_for("file:///a/b.jsx"), "javascriptreact");
|
||||
// C and C++ are separate, and neither is Rust.
|
||||
assert_eq!(rust.language_id_for("file:///a/b.c"), "c");
|
||||
assert_eq!(rust.language_id_for("file:///a/b.cpp"), "cpp");
|
||||
|
||||
// The fallback is *this server's* language. Everything unrecognized used to claim `rust`,
|
||||
// so a `.vue` file opened against a Vue server announced itself as Rust.
|
||||
assert_eq!(client("vue").language_id_for("file:///a/b.vue"), "vue");
|
||||
assert_eq!(client("vue").language_id_for("file:///a/noextension"), "vue");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unchanged_content_hashes_match() {
|
||||
assert_eq!(hash_content("fn main() {}"), hash_content("fn main() {}"));
|
||||
assert_ne!(hash_content("fn main() {}"), hash_content("fn main() { }"));
|
||||
}
|
||||
|
||||
/// The capability object decides whether a read asks or waits, so a shape that is not an
|
||||
/// object must not be read as one: `false` and a missing key both mean push-only, and a
|
||||
/// truthiness check on the JSON would have turned the first into a pull server.
|
||||
#[test]
|
||||
fn a_pull_provider_is_read_from_the_capability_object_only() {
|
||||
let with = serde_json::json!({
|
||||
"capabilities": { "diagnosticProvider": {
|
||||
"identifier": "typescript", "interFileDependencies": true
|
||||
}}
|
||||
});
|
||||
assert_eq!(pull_provider(&with).unwrap().identifier.as_deref(), Some("typescript"));
|
||||
|
||||
// An options object without an identifier is still a pull server; the request omits it.
|
||||
let bare = serde_json::json!({ "capabilities": { "diagnosticProvider": {} } });
|
||||
assert_eq!(pull_provider(&bare).unwrap().identifier, None);
|
||||
|
||||
for push_only in [
|
||||
serde_json::json!({ "capabilities": {} }),
|
||||
serde_json::json!({ "capabilities": { "diagnosticProvider": false } }),
|
||||
serde_json::json!({ "capabilities": { "diagnosticProvider": true } }),
|
||||
serde_json::json!({ "capabilities": { "diagnosticProvider": null } }),
|
||||
serde_json::json!({}),
|
||||
] {
|
||||
assert!(pull_provider(&push_only).is_none(), "not a pull provider: {push_only}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Push wins where it is offered, and silence is not an answer.
|
||||
#[test]
|
||||
fn only_a_document_the_server_has_said_nothing_about_is_asked_about() {
|
||||
let mut client = LspClient::new(config());
|
||||
let uri = "file:///tmp/a.ts";
|
||||
|
||||
// No advertised provider: there is nothing to ask, whatever the cache holds.
|
||||
assert!(!client.pulls_diagnostics_for(uri));
|
||||
|
||||
client.pull_diagnostics = Some(PullProvider { identifier: None });
|
||||
assert!(client.pulls_diagnostics_for(uri));
|
||||
|
||||
// An empty push is the server saying "clean" — an answer, so it is not asked again.
|
||||
{
|
||||
let mut inner = client.shared.inner.lock().expect("state");
|
||||
inner.diagnostics.insert(uri.to_string(), Vec::new());
|
||||
}
|
||||
assert!(!client.pulls_diagnostics_for(uri));
|
||||
assert!(client.pulls_diagnostics_for("file:///tmp/b.ts"));
|
||||
}
|
||||
|
||||
/// A pulled answer is only read where the server pushed nothing — it never shadows a push.
|
||||
#[test]
|
||||
fn a_pushed_answer_outranks_a_pulled_one() {
|
||||
let mut client = LspClient::new(config());
|
||||
let uri = "file:///tmp/a.ts";
|
||||
let pulled = Diagnostic {
|
||||
range: Range {
|
||||
start: Position { line: 0, character: 0 },
|
||||
end: Position { line: 0, character: 1 },
|
||||
},
|
||||
severity: None,
|
||||
source: None,
|
||||
code: None,
|
||||
message: "pulled".to_string(),
|
||||
};
|
||||
client.pulled.insert(uri.to_string(), PulledReport { result_id: None, items: vec![pulled] });
|
||||
assert_eq!(client.cached_diagnostics(uri)[0].message, "pulled");
|
||||
|
||||
{
|
||||
let mut inner = client.shared.inner.lock().expect("state");
|
||||
inner.diagnostics.insert(uri.to_string(), Vec::new());
|
||||
}
|
||||
assert!(client.cached_diagnostics(uri).is_empty(), "the push is the answer");
|
||||
}
|
||||
|
||||
/// A server that answers `initialize`, then reads on and answers nothing, `exit` included.
|
||||
#[cfg(unix)]
|
||||
fn deaf_server(dir: &std::path::Path) -> LspConfig {
|
||||
let script = dir.join("deaf.py");
|
||||
std::fs::write(
|
||||
&script,
|
||||
r#"
|
||||
import json, sys
|
||||
def read_msg():
|
||||
header = b""
|
||||
while b"\r\n\r\n" not in header:
|
||||
b = sys.stdin.buffer.read(1)
|
||||
if not b: return None
|
||||
header += b
|
||||
n = int([l for l in header.split(b"\r\n") if l.lower().startswith(b"content-length:")][0].split(b":")[1])
|
||||
return json.loads(sys.stdin.buffer.read(n))
|
||||
while True:
|
||||
msg = read_msg()
|
||||
if msg is None: break
|
||||
if msg.get("method") == "initialize":
|
||||
data = json.dumps({"jsonrpc": "2.0", "id": msg["id"], "result": {"capabilities": {}}}).encode()
|
||||
sys.stdout.buffer.write(b"Content-Length: %d\r\n\r\n" % len(data) + data)
|
||||
sys.stdout.buffer.flush()
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
LspConfig {
|
||||
command: vec!["python3".into(), script.display().to_string()],
|
||||
server_id: "deaf".into(),
|
||||
root_path: dir.to_path_buf(),
|
||||
init_timeout: Duration::from_secs(10),
|
||||
}
|
||||
}
|
||||
|
||||
/// Shutting down a server that ignores `exit` ends, by killing it, instead of waiting forever.
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn a_server_that_ignores_exit_is_killed_at_shutdown() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut client = LspClient::new(deaf_server(dir.path()));
|
||||
client.initialize().await.expect("handshake");
|
||||
let pid = client.child_id().expect("running");
|
||||
|
||||
let started = Instant::now();
|
||||
timeout(Duration::from_secs(10), client.shutdown()).await.expect("bounded").unwrap();
|
||||
assert!(started.elapsed() < Duration::from_secs(5), "{:?}", started.elapsed());
|
||||
assert!(!luxe_core::program::process_is_alive(pid), "the server was reaped");
|
||||
}
|
||||
|
||||
/// A request given up on leaves nothing behind in the pending map.
|
||||
///
|
||||
/// The break this catches: the entry was removed only after an answer, so a dropped request
|
||||
/// future, as a tool timeout drops it, left it there until the server exited.
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn an_abandoned_request_leaves_no_pending_entry() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut client = LspClient::new(deaf_server(dir.path()));
|
||||
client.initialize().await.expect("handshake");
|
||||
|
||||
let asked = timeout(
|
||||
Duration::from_millis(200),
|
||||
client.send_request("textDocument/hover", serde_json::json!({})),
|
||||
)
|
||||
.await;
|
||||
assert!(asked.is_err(), "the deaf server never answers");
|
||||
assert!(client.pending_requests.lock().await.is_empty(), "the entry went with the request");
|
||||
client.shutdown().await.unwrap();
|
||||
}
|
||||
|
||||
/// A client whose handshake failed does not report that it can be asked.
|
||||
///
|
||||
/// The break this catches: the state became `Initialized` right after the spawn, so a failed
|
||||
/// handshake left a client that answered as ready and failed each request on a dead pipe instead.
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn a_failed_handshake_leaves_the_client_uninitialized() {
|
||||
let mut client = LspClient::new(LspConfig {
|
||||
command: vec!["sh".into(), "-c".into(), "exit 3".into()],
|
||||
server_id: "gone".into(),
|
||||
root_path: PathBuf::from("/tmp"),
|
||||
init_timeout: Duration::from_secs(10),
|
||||
});
|
||||
assert!(client.initialize().await.is_err());
|
||||
assert_eq!(client.state, ClientState::Uninitialized);
|
||||
let asked = client.send_request("textDocument/hover", serde_json::json!({})).await;
|
||||
assert!(matches!(asked, Err(LspError::NotInitialized)), "{asked:?}");
|
||||
}
|
||||
189
crates/luxe-lsp/src/client/transport.rs
Normal file
189
crates/luxe-lsp/src/client/transport.rs
Normal file
@@ -0,0 +1,189 @@
|
||||
//! Background reader task — frames server stdout and dispatches messages.
|
||||
//!
|
||||
//! The reader owns the live server→client stream: it routes responses to their pending request,
|
||||
//! auto-replies to server→client requests (so `$/progress`, capability registration, and config
|
||||
//! requests don't stall the server), and folds `publishDiagnostics` + `$/progress` into the shared
|
||||
//! [`SharedState`] so a warm client can report settled diagnostics without a one-shot wait.
|
||||
|
||||
use super::*;
|
||||
use luxe_core::jsonrpc_frame::{read_frame, write_frame, MAX_FRAME_BYTES};
|
||||
|
||||
/// Background reader: continuously read messages from stdout and dispatch them.
|
||||
pub(crate) async fn read_loop<R: AsyncReadExt + AsyncBufRead + Unpin>(
|
||||
reader: &mut R,
|
||||
shared: Arc<SharedState>,
|
||||
stdin: Arc<Mutex<ChildStdin>>,
|
||||
tx: mpsc::Sender<JsonRpcMessage>,
|
||||
pending_requests: PendingRequests,
|
||||
) -> Result<(), LspError> {
|
||||
let outcome = route_messages(reader, shared, stdin, tx, &pending_requests).await;
|
||||
// The reader is the only thing that can ever answer an in-flight request, so when it stops —
|
||||
// EOF because the server exited, or a transport error — nothing is coming for any of them.
|
||||
// Dropping the senders turns each waiter's `rx.await` into `RequestCancelled`; left alive, a
|
||||
// server that died mid-session would leave its turn waiting forever instead of failing
|
||||
pending_requests.lock().await.clear();
|
||||
outcome
|
||||
}
|
||||
|
||||
/// The reader's loop proper, split out so [`read_loop`] can clean up on every exit path.
|
||||
async fn route_messages<R: AsyncReadExt + AsyncBufRead + Unpin>(
|
||||
reader: &mut R,
|
||||
shared: Arc<SharedState>,
|
||||
stdin: Arc<Mutex<ChildStdin>>,
|
||||
tx: mpsc::Sender<JsonRpcMessage>,
|
||||
pending_requests: &PendingRequests,
|
||||
) -> Result<(), LspError> {
|
||||
loop {
|
||||
let Some(bytes) = read_frame(reader, MAX_FRAME_BYTES).await? else {
|
||||
break; // EOF — server exited.
|
||||
};
|
||||
let msg: JsonRpcMessage = match serde_json::from_slice(&bytes) {
|
||||
Ok(msg) => msg,
|
||||
Err(e) => {
|
||||
debug!(error = %e, "lsp: dropping unparseable server message");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
match (&msg.id, &msg.method) {
|
||||
// Response to one of our requests: id present, no method.
|
||||
(Some(id), None) => {
|
||||
if let Some(id) = id.as_u64() {
|
||||
if let Some(sender) = pending_requests.lock().await.remove(&id) {
|
||||
// A JSON-RPC failure carries `error` and no `result`. Reading only
|
||||
// `result` turned every server error into `Null`, which each caller then
|
||||
// rendered as an empty answer: "No definition found" for a server that had
|
||||
// in fact said "Could not find a valid TypeScript installation".
|
||||
let _ = sender.send(match &msg.error {
|
||||
Some(error) => Err(error.clone()),
|
||||
None => Ok(msg.result.clone().unwrap_or(Value::Null)),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
// Server→client request: id and method both present. Reply so it never blocks.
|
||||
(Some(id), Some(method)) => {
|
||||
reply_to_server_request(&stdin, id.clone(), method, msg.params.as_ref()).await;
|
||||
}
|
||||
// Notification: method, no id.
|
||||
(None, Some(method)) => {
|
||||
apply_notification(&shared, method, msg.params.as_ref());
|
||||
// Best-effort tap for `wait_for_notification`; never block the reader on a full tap.
|
||||
let _ = tx.try_send(msg);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Folds a server notification into shared state: diagnostics cache + progress tracking.
|
||||
fn apply_notification(shared: &SharedState, method: &str, params: Option<&Value>) {
|
||||
match method {
|
||||
"textDocument/publishDiagnostics" => {
|
||||
let Some(params) = params else { return };
|
||||
let Some(uri) = params.get("uri").and_then(Value::as_str) else { return };
|
||||
let diagnostics = params
|
||||
.get("diagnostics")
|
||||
.and_then(Value::as_array)
|
||||
.map(|raw| {
|
||||
raw.iter()
|
||||
.filter_map(|d| match serde_json::from_value::<Diagnostic>(d.clone()) {
|
||||
Ok(diag) => Some(diag),
|
||||
Err(e) => {
|
||||
debug!(uri, error = %e, "lsp: dropping unparseable diagnostic");
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
{
|
||||
let mut inner = shared.inner.lock().expect("diagnostics state poisoned");
|
||||
inner.diagnostics.insert(uri.to_string(), diagnostics);
|
||||
inner.publish_count += 1;
|
||||
inner.mark_change();
|
||||
}
|
||||
shared.notify.notify_waiters();
|
||||
}
|
||||
"$/progress" => {
|
||||
let kind = params
|
||||
.and_then(|p| p.get("value"))
|
||||
.and_then(|v| v.get("kind"))
|
||||
.and_then(Value::as_str);
|
||||
let mut inner = shared.inner.lock().expect("diagnostics state poisoned");
|
||||
match kind {
|
||||
Some("begin") => inner.progress_active += 1,
|
||||
Some("end") => {
|
||||
inner.progress_active = inner.progress_active.saturating_sub(1);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
inner.mark_change();
|
||||
drop(inner);
|
||||
shared.notify.notify_waiters();
|
||||
}
|
||||
// Server-surfaced messages: keep Error/Warning ones so an empty diagnostics result from a
|
||||
// misconfigured/incompatible server (e.g. tsserver that can't find a usable TypeScript)
|
||||
// isn't silent. Info/log chatter (type >= 3) is ignored.
|
||||
"window/showMessage" | "window/logMessage" => {
|
||||
let Some(params) = params else { return };
|
||||
let severity = params.get("type").and_then(Value::as_u64).unwrap_or(0);
|
||||
if severity == 1 || severity == 2 {
|
||||
if let Some(message) = params.get("message").and_then(Value::as_str) {
|
||||
if let Ok(mut inner) = shared.inner.lock() {
|
||||
inner.push_notice(severity as u8, message.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// rust-analyzer's readiness signal: `quiescent: true` once indexing/priming settles.
|
||||
"experimental/serverStatus" => {
|
||||
let quiescent =
|
||||
params.and_then(|p| p.get("quiescent")).and_then(Value::as_bool).unwrap_or(false);
|
||||
{
|
||||
let mut inner = shared.inner.lock().expect("diagnostics state poisoned");
|
||||
inner.quiescent = quiescent;
|
||||
inner.mark_change();
|
||||
}
|
||||
shared.notify.notify_waiters();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Auto-replies to a server→client request so the server never stalls waiting on us.
|
||||
///
|
||||
/// We don't implement these capabilities, so the replies are deliberately empty: `null` for
|
||||
/// capability registration / progress-create / message requests, and an array of `null`s for
|
||||
/// `workspace/configuration` (the server then falls back to defaults).
|
||||
async fn reply_to_server_request(
|
||||
stdin: &Arc<Mutex<ChildStdin>>,
|
||||
id: Value,
|
||||
method: &str,
|
||||
params: Option<&Value>,
|
||||
) {
|
||||
let result = if method == "workspace/configuration" {
|
||||
let items = params
|
||||
.and_then(|p| p.get("items"))
|
||||
.and_then(Value::as_array)
|
||||
.map_or(1, |items| items.len());
|
||||
Value::Array(vec![Value::Null; items.max(1)])
|
||||
} else {
|
||||
Value::Null
|
||||
};
|
||||
|
||||
let response = JsonRpcMessage {
|
||||
jsonrpc: "2.0".to_string(),
|
||||
id: Some(id),
|
||||
method: None,
|
||||
params: None,
|
||||
result: Some(result),
|
||||
error: None,
|
||||
};
|
||||
let Ok(json) = serde_json::to_string(&response) else { return };
|
||||
let mut guard = stdin.lock().await;
|
||||
if let Err(e) = write_frame(&mut *guard, json.as_bytes()).await {
|
||||
debug!(method, error = %e, "lsp: failed to reply to server request");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user