1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use tokio::process::Command;
use super::client::JsonRpcClient;
use super::language::LanguageConfig;
use super::types::{Diagnostic, RawDiagnostic};
/// An active LSP server process with JSON-RPC communication.
pub(super) struct LspServer {
client: JsonRpcClient,
/// Per-file version counters (LSP requires strictly increasing versions).
file_versions: HashMap<PathBuf, i32>,
/// Diagnostics version baseline recorded before each `didOpen`/`didChange`.
/// `pull_diagnostics` waits for a version *newer* than this.
baseline_versions: HashMap<PathBuf, u64>,
/// Workspace root used during initialization.
_root_uri: String,
/// Child process handle — dropped when server is dropped (kills process).
_child: tokio::process::Child,
}
impl LspServer {
/// Spawn and initialize an LSP server.
///
/// Sends `initialize` + `initialized` before returning.
/// Returns `Err` if the server fails to start or initialize.
pub async fn spawn(config: &LanguageConfig, workspace_root: &Path) -> Result<Self, String> {
let mut child = Command::new(config.command)
.args(config.args)
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::null())
.kill_on_drop(true)
.spawn()
.map_err(|e| format!("failed to spawn {}: {e}", config.command))?;
let stdin = child.stdin.take().ok_or("failed to capture stdin")?;
let stdout = child.stdout.take().ok_or("failed to capture stdout")?;
let client = JsonRpcClient::new(stdin, stdout);
let root_uri = format!("file://{}", workspace_root.display());
// Send initialize request
let init_params = serde_json::json!({
"processId": std::process::id(),
"rootUri": root_uri,
"capabilities": {
"textDocument": {
"publishDiagnostics": {
"relatedInformation": false
}
}
}
});
let _init_result = tokio::time::timeout(
std::time::Duration::from_secs(10),
client.request("initialize", init_params),
)
.await
.map_err(|_| "initialize timed out".to_string())?
.map_err(|e| format!("initialize failed: {e}"))?;
// Send initialized notification
client
.notify("initialized", serde_json::json!({}))
.await
.map_err(|e| format!("initialized notification failed: {e}"))?;
Ok(Self {
client,
file_versions: HashMap::new(),
baseline_versions: HashMap::new(),
_root_uri: root_uri,
_child: child,
})
}
/// Notify the server that a file was changed (opened or modified).
///
/// If this is the first time we're notifying about this file, sends
/// `textDocument/didOpen`. Otherwise sends `textDocument/didChange`.
/// Records the current diagnostics version before sending so that
/// `pull_diagnostics` can wait for a *newer* notification.
pub async fn notify_file_changed(&mut self, path: &Path, content: &str) -> Result<(), String> {
let uri = format!("file://{}", path.display());
let lang_id = super::language::detect_language(path).unwrap_or("plaintext");
// Record the current diagnostics version *before* the notification.
// pull_diagnostics will wait for version > this baseline.
let baseline = self.client.diagnostics_version_for(&uri).await;
self.baseline_versions.insert(path.to_path_buf(), baseline);
let version = self.file_versions.entry(path.to_path_buf()).or_insert(0);
if *version == 0 {
// First time: didOpen (version starts at 1)
*version = 1;
self.client
.notify(
"textDocument/didOpen",
serde_json::json!({
"textDocument": {
"uri": uri,
"languageId": lang_id,
"version": *version,
"text": content,
}
}),
)
.await?;
} else {
// Subsequent: didChange (full sync, strictly increasing version)
*version += 1;
self.client
.notify(
"textDocument/didChange",
serde_json::json!({
"textDocument": {
"uri": uri,
"version": *version,
},
"contentChanges": [{
"text": content,
}]
}),
)
.await?;
}
Ok(())
}
/// Request diagnostics for a file.
///
/// Tries the pull model (`textDocument/diagnostic`, LSP 3.17) first.
/// If the server doesn't support it (e.g., rust-analyzer), falls back to
/// cached `publishDiagnostics` notifications (push model).
///
/// For the push model, uses version-based tracking: waits for notifications
/// *newer* than the baseline recorded in `notify_file_changed`. If a
/// notification arrives with empty diagnostics (e.g., syntax-only pass),
/// records the new version and waits again for type-checking results.
/// Total push-model timeout: 30 seconds.
pub async fn pull_diagnostics(&self, path: &Path) -> Vec<Diagnostic> {
let uri = format!("file://{}", path.display());
let baseline = self.baseline_versions.get(path).copied().unwrap_or(0);
// Small debounce to let the server start processing the file change
tokio::time::sleep(std::time::Duration::from_millis(250)).await;
// Try pull model first (LSP 3.17 textDocument/diagnostic)
let result = tokio::time::timeout(
std::time::Duration::from_secs(3),
self.client.request(
"textDocument/diagnostic",
serde_json::json!({
"textDocument": { "uri": uri }
}),
),
)
.await;
match &result {
Ok(Ok(value)) => {
let diagnostics = parse_diagnostic_response(value);
if !diagnostics.is_empty() {
tracing::debug!(
uri = %uri,
count = diagnostics.len(),
"pull model returned diagnostics"
);
return diagnostics;
}
tracing::debug!(uri = %uri, "pull model returned empty, trying push model");
}
Ok(Err(e)) => {
tracing::debug!(uri = %uri, error = %e, "pull model request failed");
}
Err(_) => {
tracing::debug!(uri = %uri, "pull model timed out");
}
}
// Fall back to push model (publishDiagnostics notifications).
// rust-analyzer sends notifications in phases:
// 1. Syntax-only pass (fast, usually empty diagnostics)
// 2. Type-checking pass (slow on cold start, has real errors)
//
// We loop: wait for the *next* notification after our baseline,
// check if it has diagnostics, and if empty keep waiting for the
// next one. Total timeout: 30s to handle cold-start workspace loading.
let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(30);
let mut current_version = baseline;
tracing::debug!(
uri = %uri,
baseline = baseline,
"waiting for publishDiagnostics (up to 30s)"
);
loop {
let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
if remaining.is_zero() {
tracing::debug!(uri = %uri, "push model timed out — no diagnostics");
return Vec::new();
}
if let Some(params) = self
.client
.wait_for_published_diagnostics(&uri, current_version, remaining)
.await
{
let diagnostics = parse_diagnostic_response(¶ms);
if !diagnostics.is_empty() {
tracing::debug!(
uri = %uri,
count = diagnostics.len(),
"push model returned diagnostics"
);
return diagnostics;
}
// Empty notification — update version and wait for the next one.
// This handles the syntax-only → type-checking progression.
let new_version = self.client.diagnostics_version_for(&uri).await;
tracing::debug!(
uri = %uri,
version = new_version,
"push model returned empty, waiting for update"
);
current_version = new_version;
} else {
tracing::debug!(uri = %uri, "push model timed out — no diagnostics");
return Vec::new();
}
}
}
}
/// Parse diagnostics from a `textDocument/diagnostic` response.
fn parse_diagnostic_response(value: &serde_json::Value) -> Vec<Diagnostic> {
// The response can be DocumentDiagnosticReport which has an `items` array
if let Some(items) = value.get("items").and_then(|v| v.as_array()) {
items
.iter()
.filter_map(|item| {
serde_json::from_value::<RawDiagnostic>(item.clone())
.ok()
.map(|r| r.into_diagnostic())
})
.collect()
} else if let Some(diagnostics) = value.get("diagnostics").and_then(|v| v.as_array()) {
// publishDiagnostics format
diagnostics
.iter()
.filter_map(|item| {
serde_json::from_value::<RawDiagnostic>(item.clone())
.ok()
.map(|r| r.into_diagnostic())
})
.collect()
} else {
Vec::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn parse_diagnostic_response_items_format() {
let value = json!({
"kind": "full",
"items": [
{
"range": {
"start": {"line": 0, "character": 0},
"end": {"line": 0, "character": 5}
},
"severity": 1,
"message": "syntax error"
}
]
});
let diagnostics = parse_diagnostic_response(&value);
assert_eq!(diagnostics.len(), 1);
assert_eq!(diagnostics[0].message, "syntax error");
}
#[test]
fn parse_diagnostic_response_diagnostics_format() {
let value = json!({
"diagnostics": [
{
"range": {
"start": {"line": 5, "character": 0},
"end": {"line": 5, "character": 3}
},
"severity": 2,
"message": "unused variable"
}
]
});
let diagnostics = parse_diagnostic_response(&value);
assert_eq!(diagnostics.len(), 1);
assert_eq!(diagnostics[0].message, "unused variable");
}
#[test]
fn parse_diagnostic_response_empty() {
let value = json!({});
let diagnostics = parse_diagnostic_response(&value);
assert!(diagnostics.is_empty());
}
#[test]
fn parse_diagnostic_response_null_items() {
let value = json!({"items": null});
let diagnostics = parse_diagnostic_response(&value);
assert!(diagnostics.is_empty());
}
}