1use super::{DevelopmentError, DevelopmentResult, read_bounded_utf8};
2use serde::{Deserialize, Serialize};
3use serde_json::Value;
4use std::{
5 collections::BTreeMap,
6 fs,
7 io::{BufRead, BufReader, Read, Write},
8 path::{Path, PathBuf},
9 process::{Child, ChildStdin, Command, Stdio},
10 sync::mpsc::{self, Receiver},
11 thread,
12 time::{Duration, Instant},
13};
14
15const MAX_LSP_MESSAGE_BYTES: usize = 4 * 1024 * 1024;
16const DIAGNOSTICS_EMPTY_GRACE: Duration = Duration::from_secs(15);
17
18#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
19#[serde(rename_all = "camelCase")]
20pub struct DiagnosticPosition {
21 pub line: u32,
22 pub character: u32,
23}
24
25#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
26#[serde(rename_all = "camelCase")]
27pub struct LanguageDiagnostic {
28 pub path: String,
29 pub start: DiagnosticPosition,
30 pub end: DiagnosticPosition,
31 pub severity: Option<u8>,
32 pub code: Option<String>,
33 pub source: Option<String>,
34 pub message: String,
35}
36
37pub struct LspClient {
41 root: PathBuf,
42 child: Child,
43 input: ChildStdin,
44 output: Receiver<Value>,
45 next_id: u64,
46 documents: BTreeMap<String, OpenDocument>,
47 shutdown: bool,
48}
49
50#[derive(Debug, Clone)]
51struct OpenDocument {
52 uri: String,
53 version: i64,
54 text: String,
55}
56
57#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
59#[serde(rename_all = "camelCase")]
60pub struct LanguageResponse {
61 pub method: String,
62 pub result: Value,
63}
64
65impl std::fmt::Debug for LspClient {
66 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
67 formatter
68 .debug_struct("LspClient")
69 .field("root", &self.root)
70 .field("pid", &self.child.id())
71 .finish()
72 }
73}
74
75impl LspClient {
76 pub fn spawn(root: &Path, server: &str, arguments: &[String]) -> DevelopmentResult<Self> {
77 let root = fs::canonicalize(root)?;
78 let mut child = Command::new(server)
79 .args(arguments)
80 .current_dir(&root)
81 .stdin(Stdio::piped())
82 .stdout(Stdio::piped())
83 .stderr(Stdio::null())
84 .spawn()
85 .map_err(|error| {
86 DevelopmentError::Process(format!(
87 "failed to start language server {server}: {error}"
88 ))
89 })?;
90 let input = child
91 .stdin
92 .take()
93 .ok_or_else(|| DevelopmentError::Process("language server stdin unavailable".into()))?;
94 let output = child.stdout.take().ok_or_else(|| {
95 DevelopmentError::Process("language server stdout unavailable".into())
96 })?;
97 let (sender, receiver) = mpsc::sync_channel(256);
98 thread::Builder::new()
99 .name("glass-lsp-reader".into())
100 .spawn(move || read_lsp_messages(output, sender))
101 .map_err(DevelopmentError::Io)?;
102 let mut client = Self {
103 root,
104 child,
105 input,
106 output: receiver,
107 next_id: 1,
108 documents: BTreeMap::new(),
109 shutdown: false,
110 };
111 client.initialize()?;
112 Ok(client)
113 }
114
115 pub fn rust_analyzer(root: &Path) -> DevelopmentResult<Self> {
116 Self::spawn(root, "rust-analyzer", &[])
117 }
118
119 pub fn diagnostics(&mut self, path: &str) -> DevelopmentResult<Vec<LanguageDiagnostic>> {
120 let relative = Path::new(path);
121 if relative.is_absolute()
122 || relative
123 .components()
124 .any(|component| matches!(component, std::path::Component::ParentDir))
125 {
126 return Err(DevelopmentError::PathOutsideWorkspace(relative.into()));
127 }
128 let uri = self.sync_document(path)?.uri.clone();
129 let deadline = Instant::now() + Duration::from_secs(30);
130 let mut empty_published_at = None;
131 while Instant::now() < deadline {
132 let remaining = deadline.saturating_duration_since(Instant::now());
133 let wait = empty_published_at
134 .map(|published: Instant| {
135 remaining.min(
136 (published + DIAGNOSTICS_EMPTY_GRACE)
137 .saturating_duration_since(Instant::now()),
138 )
139 })
140 .unwrap_or(remaining);
141 let value = match self.output.recv_timeout(wait) {
142 Ok(value) => value,
143 Err(mpsc::RecvTimeoutError::Timeout) if empty_published_at.is_some() => {
144 return Ok(Vec::new());
145 }
146 Err(error) => {
147 return Err(DevelopmentError::Process(format!(
148 "language diagnostics timed out: {error}"
149 )));
150 }
151 };
152 if value.get("method").and_then(Value::as_str)
153 != Some("textDocument/publishDiagnostics")
154 || value.pointer("/params/uri").and_then(Value::as_str) != Some(uri.as_str())
155 {
156 continue;
157 }
158 let diagnostics = value
159 .pointer("/params/diagnostics")
160 .and_then(Value::as_array)
161 .ok_or_else(|| {
162 DevelopmentError::Serialization(
163 "language server diagnostics must be an array".into(),
164 )
165 })?;
166 if diagnostics.is_empty() {
167 empty_published_at = Some(Instant::now());
168 continue;
169 }
170 return diagnostics
171 .iter()
172 .take(512)
173 .map(|diagnostic| parse_diagnostic(path, diagnostic))
174 .collect();
175 }
176 Err(DevelopmentError::Process(
177 "language diagnostics timed out".into(),
178 ))
179 }
180
181 pub fn sync_document(&mut self, path: &str) -> DevelopmentResult<LanguageDocument> {
183 let (absolute, normalized) = self.resolve_document(path)?;
184 let text = read_bounded_utf8(&absolute, super::MAX_BUFFER_BYTES, "language document")?;
185 if let Some(document) = self.documents.get_mut(&normalized) {
186 if document.text != text {
187 document.version = document.version.saturating_add(1);
188 document.text = text;
189 let notification = serde_json::json!({
190 "jsonrpc": "2.0", "method": "textDocument/didChange",
191 "params": {"textDocument": {"uri": document.uri, "version": document.version},
192 "contentChanges": [{"text": document.text}]}
193 });
194 self.notify(notification)?;
195 }
196 } else {
197 let uri = file_uri(&absolute)?;
198 self.notify(serde_json::json!({
199 "jsonrpc": "2.0", "method": "textDocument/didOpen",
200 "params": {"textDocument": {"uri": uri, "languageId": language_id(&absolute),
201 "version": 1, "text": text}}
202 }))?;
203 self.documents.insert(
204 normalized.clone(),
205 OpenDocument {
206 uri,
207 version: 1,
208 text,
209 },
210 );
211 }
212 let document = self.documents.get(&normalized).expect("inserted above");
213 Ok(LanguageDocument {
214 uri: document.uri.clone(),
215 version: document.version,
216 })
217 }
218
219 pub fn save_document(&mut self, path: &str) -> DevelopmentResult<()> {
220 let document = self.sync_document(path)?;
221 let uri = document.uri.clone();
222 self.notify(serde_json::json!({"jsonrpc":"2.0","method":"textDocument/didSave","params":{"textDocument":{"uri":uri}}}))
223 }
224
225 pub fn close_document(&mut self, path: &str) -> DevelopmentResult<()> {
226 let (_, normalized) = self.resolve_document(path)?;
227 let document = self
228 .documents
229 .remove(&normalized)
230 .ok_or_else(|| DevelopmentError::NotFound(format!("open language document {path}")))?;
231 self.notify(serde_json::json!({"jsonrpc":"2.0","method":"textDocument/didClose","params":{"textDocument":{"uri":document.uri}}}))
232 }
233
234 pub fn hover(
235 &mut self,
236 path: &str,
237 line: u32,
238 character: u32,
239 ) -> DevelopmentResult<LanguageResponse> {
240 self.position_request("textDocument/hover", path, line, character, Value::Null)
241 }
242
243 pub fn definition(
244 &mut self,
245 path: &str,
246 line: u32,
247 character: u32,
248 ) -> DevelopmentResult<LanguageResponse> {
249 self.position_request(
250 "textDocument/definition",
251 path,
252 line,
253 character,
254 Value::Null,
255 )
256 }
257
258 pub fn declaration(
259 &mut self,
260 path: &str,
261 line: u32,
262 character: u32,
263 ) -> DevelopmentResult<LanguageResponse> {
264 self.position_request(
265 "textDocument/declaration",
266 path,
267 line,
268 character,
269 Value::Null,
270 )
271 }
272
273 pub fn implementation(
274 &mut self,
275 path: &str,
276 line: u32,
277 character: u32,
278 ) -> DevelopmentResult<LanguageResponse> {
279 self.position_request(
280 "textDocument/implementation",
281 path,
282 line,
283 character,
284 Value::Null,
285 )
286 }
287
288 pub fn references(
289 &mut self,
290 path: &str,
291 line: u32,
292 character: u32,
293 ) -> DevelopmentResult<LanguageResponse> {
294 self.position_request(
295 "textDocument/references",
296 path,
297 line,
298 character,
299 serde_json::json!({"includeDeclaration": true}),
300 )
301 }
302
303 pub fn document_symbols(&mut self, path: &str) -> DevelopmentResult<LanguageResponse> {
304 let uri = self.sync_document(path)?.uri.clone();
305 self.request_result(
306 "textDocument/documentSymbol",
307 serde_json::json!({"textDocument":{"uri":uri}}),
308 )
309 }
310
311 pub fn workspace_symbols(&mut self, query: &str) -> DevelopmentResult<LanguageResponse> {
312 validate_lsp_text("workspace symbol query", query, 1024, true)?;
313 self.request_result("workspace/symbol", serde_json::json!({"query":query}))
314 }
315
316 pub fn completion(
317 &mut self,
318 path: &str,
319 line: u32,
320 character: u32,
321 ) -> DevelopmentResult<LanguageResponse> {
322 self.position_request(
323 "textDocument/completion",
324 path,
325 line,
326 character,
327 serde_json::json!({"context":{"triggerKind":1}}),
328 )
329 }
330
331 pub fn signature_help(
332 &mut self,
333 path: &str,
334 line: u32,
335 character: u32,
336 ) -> DevelopmentResult<LanguageResponse> {
337 self.position_request(
338 "textDocument/signatureHelp",
339 path,
340 line,
341 character,
342 serde_json::json!({"context":{"triggerKind":1,"isRetrigger":false}}),
343 )
344 }
345
346 pub fn code_actions(
347 &mut self,
348 path: &str,
349 start: DiagnosticPosition,
350 end: DiagnosticPosition,
351 diagnostics: &[Value],
352 ) -> DevelopmentResult<LanguageResponse> {
353 if diagnostics.len() > 512 {
354 return Err(DevelopmentError::InvalidInput(
355 "code action diagnostics exceed the 512 item limit".into(),
356 ));
357 }
358 let uri = self.sync_document(path)?.uri.clone();
359 self.request_result(
360 "textDocument/codeAction",
361 serde_json::json!({
362 "textDocument":{"uri":uri},
363 "range":{"start":protocol_position(&start),"end":protocol_position(&end)},
364 "context":{"diagnostics":diagnostics}
365 }),
366 )
367 }
368
369 pub fn formatting(&mut self, path: &str) -> DevelopmentResult<LanguageResponse> {
370 let uri = self.sync_document(path)?.uri.clone();
371 self.request_result("textDocument/formatting", serde_json::json!({"textDocument":{"uri":uri},"options":{"tabSize":4,"insertSpaces":true}}))
372 }
373
374 pub fn range_formatting(
375 &mut self,
376 path: &str,
377 start: DiagnosticPosition,
378 end: DiagnosticPosition,
379 ) -> DevelopmentResult<LanguageResponse> {
380 let uri = self.sync_document(path)?.uri.clone();
381 self.request_result(
382 "textDocument/rangeFormatting",
383 serde_json::json!({
384 "textDocument":{"uri":uri},
385 "range":{"start":protocol_position(&start),"end":protocol_position(&end)},
386 "options":{"tabSize":4,"insertSpaces":true}
387 }),
388 )
389 }
390
391 pub fn semantic_tokens(&mut self, path: &str) -> DevelopmentResult<LanguageResponse> {
392 let uri = self.sync_document(path)?.uri.clone();
393 self.request_result(
394 "textDocument/semanticTokens/full",
395 serde_json::json!({"textDocument":{"uri":uri}}),
396 )
397 }
398
399 pub fn raw_request(
402 &mut self,
403 method: &str,
404 params: Value,
405 timeout: Duration,
406 ) -> DevelopmentResult<LanguageResponse> {
407 validate_lsp_text("LSP method", method, 256, false)?;
408 if !method.contains('/')
409 || matches!(
410 method,
411 "initialize" | "initialized" | "shutdown" | "exit" | "$/cancelRequest"
412 )
413 || method.starts_with("window/")
414 {
415 return Err(DevelopmentError::InvalidInput(
416 "raw LSP requests cannot control lifecycle or server UI".into(),
417 ));
418 }
419 if timeout.is_zero() || timeout > Duration::from_secs(60) {
420 return Err(DevelopmentError::InvalidInput(
421 "raw LSP timeout must be between 1 ms and 60 seconds".into(),
422 ));
423 }
424 if serde_json::to_vec(¶ms)?.len() > MAX_LSP_MESSAGE_BYTES {
425 return Err(DevelopmentError::InvalidInput(
426 "raw LSP parameters exceed the size limit".into(),
427 ));
428 }
429 let response = self.call(method, params, timeout)?;
430 if let Some(error) = response.get("error") {
431 return Err(DevelopmentError::Process(format!(
432 "{method} failed: {error}"
433 )));
434 }
435 Ok(LanguageResponse {
436 method: method.into(),
437 result: response.get("result").cloned().unwrap_or(Value::Null),
438 })
439 }
440
441 pub fn rename(
442 &mut self,
443 path: &str,
444 line: u32,
445 character: u32,
446 new_name: &str,
447 ) -> DevelopmentResult<LanguageResponse> {
448 if new_name.is_empty() || new_name.len() > 256 {
449 return Err(DevelopmentError::InvalidInput(
450 "rename target must be 1 to 256 bytes".into(),
451 ));
452 }
453 self.position_request(
454 "textDocument/rename",
455 path,
456 line,
457 character,
458 serde_json::json!({"newName":new_name}),
459 )
460 }
461
462 fn position_request(
463 &mut self,
464 method: &str,
465 path: &str,
466 line: u32,
467 character: u32,
468 extra: Value,
469 ) -> DevelopmentResult<LanguageResponse> {
470 let uri = self.sync_document(path)?.uri.clone();
471 let mut params = serde_json::json!({"textDocument":{"uri":uri},"position":{"line":line.saturating_sub(1),"character":character.saturating_sub(1)}});
472 if let (Some(target), Some(source)) = (params.as_object_mut(), extra.as_object()) {
473 target.extend(source.clone());
474 }
475 self.request_result(method, params)
476 }
477
478 fn request_result(
479 &mut self,
480 method: &str,
481 params: Value,
482 ) -> DevelopmentResult<LanguageResponse> {
483 let response = self.call(method, params, Duration::from_secs(15))?;
484 if let Some(error) = response.get("error") {
485 return Err(DevelopmentError::Process(format!(
486 "{method} failed: {error}"
487 )));
488 }
489 let result = response.get("result").cloned().unwrap_or(Value::Null);
490 if serde_json::to_vec(&result)?.len() > MAX_LSP_MESSAGE_BYTES {
491 return Err(DevelopmentError::Serialization(
492 "language response exceeds the size limit".into(),
493 ));
494 }
495 Ok(LanguageResponse {
496 method: method.into(),
497 result,
498 })
499 }
500
501 fn resolve_document(&self, path: &str) -> DevelopmentResult<(PathBuf, String)> {
502 let relative = Path::new(path);
503 if relative.is_absolute()
504 || relative
505 .components()
506 .any(|part| matches!(part, std::path::Component::ParentDir))
507 {
508 return Err(DevelopmentError::PathOutsideWorkspace(relative.into()));
509 }
510 let absolute = fs::canonicalize(self.root.join(relative))?;
511 if !absolute.starts_with(&self.root) {
512 return Err(DevelopmentError::PathOutsideWorkspace(absolute));
513 }
514 Ok((absolute, relative.to_string_lossy().into_owned()))
515 }
516
517 fn initialize(&mut self) -> DevelopmentResult<()> {
518 let root_uri = file_uri(&self.root)?;
519 let response = self.call(
520 "initialize",
521 serde_json::json!({
522 "processId": std::process::id(),
523 "rootUri": root_uri,
524 "capabilities": {
525 "workspace": {"workspaceEdit": {"documentChanges": true}},
526 "textDocument": {
527 "publishDiagnostics": {"relatedInformation": true},
528 "completion": {"completionItem": {"snippetSupport": false}},
529 "signatureHelp": {},
530 "codeAction": {"dataSupport": true},
531 "rename": {"prepareSupport": true},
532 "semanticTokens": {"requests": {"full": true}, "tokenTypes": [], "tokenModifiers": [], "formats": ["relative"]}
533 }
534 },
535 "workspaceFolders": [{"uri": root_uri, "name": self.root.file_name().and_then(|name| name.to_str()).unwrap_or("project")}]
536 }),
537 Duration::from_secs(30),
538 )?;
539 if response.get("error").is_some() {
540 return Err(DevelopmentError::Process(format!(
541 "language server initialization failed: {}",
542 response["error"]
543 )));
544 }
545 self.notify(serde_json::json!({
546 "jsonrpc": "2.0",
547 "method": "initialized",
548 "params": {}
549 }))
550 }
551
552 fn call(&mut self, method: &str, params: Value, timeout: Duration) -> DevelopmentResult<Value> {
553 let id = self.next_id;
554 self.next_id = self.next_id.saturating_add(1);
555 self.notify(serde_json::json!({
556 "jsonrpc": "2.0",
557 "id": id,
558 "method": method,
559 "params": params
560 }))?;
561 let deadline = Instant::now() + timeout;
562 loop {
563 let value = self
564 .output
565 .recv_timeout(deadline.saturating_duration_since(Instant::now()))
566 .map_err(|error| {
567 DevelopmentError::Process(format!(
568 "language server response timed out: {error}"
569 ))
570 })?;
571 if value.get("id").and_then(Value::as_u64) == Some(id) {
572 return Ok(value);
573 }
574 }
575 }
576
577 fn notify(&mut self, value: Value) -> DevelopmentResult<()> {
578 let body = serde_json::to_vec(&value)?;
579 if body.len() > MAX_LSP_MESSAGE_BYTES {
580 return Err(DevelopmentError::InvalidInput(
581 "language protocol message exceeds the size limit".into(),
582 ));
583 }
584 write!(self.input, "Content-Length: {}\r\n\r\n", body.len())?;
585 self.input.write_all(&body)?;
586 self.input.flush()?;
587 Ok(())
588 }
589}
590
591impl Drop for LspClient {
592 fn drop(&mut self) {
593 if !self.shutdown {
594 let _ = self.call("shutdown", Value::Null, Duration::from_secs(2));
595 self.shutdown = true;
596 }
597 let _ = self.notify(serde_json::json!({
598 "jsonrpc": "2.0",
599 "method": "exit",
600 "params": null
601 }));
602 let _ = self.child.kill();
603 let _ = self.child.wait();
604 }
605}
606
607#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
609#[serde(rename_all = "camelCase")]
610pub struct LanguageDocument {
611 pub uri: String,
612 pub version: i64,
613}
614
615fn read_lsp_messages(output: impl Read, sender: mpsc::SyncSender<Value>) {
616 let mut reader = BufReader::new(output);
617 loop {
618 let mut content_length = None;
619 loop {
620 let mut header = String::new();
621 match reader.read_line(&mut header) {
622 Ok(0) | Err(_) => return,
623 Ok(_) if header == "\r\n" || header == "\n" => break,
624 Ok(_) => {
625 if let Some(value) = header
626 .strip_prefix("Content-Length:")
627 .and_then(|value| value.trim().parse::<usize>().ok())
628 {
629 content_length = Some(value);
630 }
631 }
632 }
633 }
634 let Some(length) = content_length.filter(|length| *length <= MAX_LSP_MESSAGE_BYTES) else {
635 return;
636 };
637 let mut body = vec![0; length];
638 if reader.read_exact(&mut body).is_err() {
639 return;
640 }
641 if let Ok(value) = serde_json::from_slice(&body)
642 && sender.send(value).is_err()
643 {
644 return;
645 }
646 }
647}
648
649fn parse_diagnostic(path: &str, value: &Value) -> DevelopmentResult<LanguageDiagnostic> {
650 let position = |pointer: &str| -> DevelopmentResult<DiagnosticPosition> {
651 let value = value.pointer(pointer).ok_or_else(|| {
652 DevelopmentError::Serialization(format!("diagnostic is missing {pointer}"))
653 })?;
654 Ok(DiagnosticPosition {
655 line: value.get("line").and_then(Value::as_u64).unwrap_or(0) as u32 + 1,
656 character: value.get("character").and_then(Value::as_u64).unwrap_or(0) as u32 + 1,
657 })
658 };
659 let code = value.get("code").and_then(|code| {
660 code.as_str()
661 .map(str::to_string)
662 .or_else(|| code.as_i64().map(|number| number.to_string()))
663 });
664 Ok(LanguageDiagnostic {
665 path: path.into(),
666 start: position("/range/start")?,
667 end: position("/range/end")?,
668 severity: value
669 .get("severity")
670 .and_then(Value::as_u64)
671 .map(|value| value as u8),
672 code,
673 source: value
674 .get("source")
675 .and_then(Value::as_str)
676 .map(str::to_string),
677 message: value
678 .get("message")
679 .and_then(Value::as_str)
680 .unwrap_or("language diagnostic")
681 .chars()
682 .take(4096)
683 .collect(),
684 })
685}
686
687fn protocol_position(position: &DiagnosticPosition) -> Value {
688 serde_json::json!({
689 "line": position.line.saturating_sub(1),
690 "character": position.character.saturating_sub(1)
691 })
692}
693
694fn validate_lsp_text(
695 description: &str,
696 value: &str,
697 limit: usize,
698 allow_empty: bool,
699) -> DevelopmentResult<()> {
700 if (!allow_empty && value.is_empty())
701 || value.len() > limit
702 || value.chars().any(char::is_control)
703 {
704 return Err(DevelopmentError::InvalidInput(format!(
705 "{description} must contain {}..={limit} non-control bytes",
706 usize::from(!allow_empty)
707 )));
708 }
709 Ok(())
710}
711
712fn file_uri(path: &Path) -> DevelopmentResult<String> {
713 url::Url::from_file_path(path)
714 .map(|url| url.to_string())
715 .map_err(|_| {
716 DevelopmentError::InvalidInput(format!(
717 "cannot represent path as URI: {}",
718 path.display()
719 ))
720 })
721}
722
723fn language_id(path: &Path) -> &'static str {
724 match path.extension().and_then(|extension| extension.to_str()) {
725 Some("rs") => "rust",
726 Some("ts" | "tsx") => "typescript",
727 Some("js" | "jsx") => "javascript",
728 Some("py") => "python",
729 Some("go") => "go",
730 _ => "plaintext",
731 }
732}
733
734#[cfg(test)]
735mod tests {
736 use super::*;
737
738 #[test]
739 fn raw_language_requests_reject_lifecycle_and_unbounded_inputs() {
740 assert!(validate_lsp_text("method", "textDocument/hover", 256, false).is_ok());
741 assert!(validate_lsp_text("method", "", 256, false).is_err());
742 assert!(validate_lsp_text("method", "textDocument\nhover", 256, false).is_err());
743 assert_eq!(
744 protocol_position(&DiagnosticPosition {
745 line: 4,
746 character: 2
747 }),
748 serde_json::json!({"line":3,"character":1})
749 );
750 }
751
752 #[test]
753 fn rust_analyzer_publishes_real_diagnostics_when_available() {
754 if !Command::new("rust-analyzer")
755 .arg("--version")
756 .output()
757 .is_ok_and(|output| output.status.success())
758 {
759 return;
760 }
761 let root = std::env::temp_dir().join(format!("glass-lsp-{}", std::process::id()));
762 let _ = fs::remove_dir_all(&root);
763 fs::create_dir_all(root.join("src")).unwrap();
764 fs::write(
765 root.join("Cargo.toml"),
766 "[package]\nname='glass_lsp_fixture'\nversion='0.1.0'\nedition='2024'\n",
767 )
768 .unwrap();
769 fs::write(root.join("src/lib.rs"), "pub fn broken( {\n").unwrap();
770 let mut client = LspClient::rust_analyzer(&root).unwrap();
771 #[cfg(unix)]
772 let server_pid = client.child.id();
773 assert_eq!(client.sync_document("src/lib.rs").unwrap().version, 1);
774 fs::write(root.join("src/lib.rs"), "pub fn broken( -> u8 {\n").unwrap();
775 assert_eq!(client.sync_document("src/lib.rs").unwrap().version, 2);
776 client.save_document("src/lib.rs").unwrap();
777 let diagnostics = client.diagnostics("src/lib.rs").unwrap();
778 assert!(
779 !diagnostics.is_empty(),
780 "rust-analyzer returned no diagnostics"
781 );
782 assert!(
783 diagnostics
784 .iter()
785 .all(|diagnostic| diagnostic.path == "src/lib.rs")
786 );
787 client.close_document("src/lib.rs").unwrap();
788 drop(client);
789 #[cfg(unix)]
790 {
791 let result = unsafe { libc::kill(server_pid as i32, 0) };
793 assert_ne!(result, 0, "language server survived client shutdown");
794 assert_eq!(
795 std::io::Error::last_os_error().raw_os_error(),
796 Some(libc::ESRCH)
797 );
798 }
799 let _ = fs::remove_dir_all(root);
800 }
801}