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