Skip to main content

glass_dev/development/
language.rs

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
37/// Minimal standards-compliant LSP client used by the Development Runtime.
38/// Language intelligence stays in external language servers; Glass owns only
39/// lifecycle, bounded framing, normalized diagnostics, and timeline routing.
40pub 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/// Bounded, method-labelled response for interactive language operations.
58#[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    /// Open a document once, then publish monotonic full-text changes.
182    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 inlay_hints(&mut self, path: &str) -> DevelopmentResult<LanguageResponse> {
332        let document = self.sync_document(path)?;
333        let uri = document.uri.clone();
334        let last_line = self
335            .documents
336            .values()
337            .find(|item| item.uri == uri)
338            .map(|item| item.text.split('\n').count().saturating_sub(1))
339            .unwrap_or(0);
340        self.request_result(
341            "textDocument/inlayHint",
342            serde_json::json!({
343                "textDocument":{"uri":uri},
344                "range":{
345                    "start":{"line":0,"character":0},
346                    "end":{"line":last_line,"character":0}
347                }
348            }),
349        )
350    }
351
352    pub fn signature_help(
353        &mut self,
354        path: &str,
355        line: u32,
356        character: u32,
357    ) -> DevelopmentResult<LanguageResponse> {
358        self.position_request(
359            "textDocument/signatureHelp",
360            path,
361            line,
362            character,
363            serde_json::json!({"context":{"triggerKind":1,"isRetrigger":false}}),
364        )
365    }
366
367    pub fn code_actions(
368        &mut self,
369        path: &str,
370        start: DiagnosticPosition,
371        end: DiagnosticPosition,
372        diagnostics: &[Value],
373    ) -> DevelopmentResult<LanguageResponse> {
374        if diagnostics.len() > 512 {
375            return Err(DevelopmentError::InvalidInput(
376                "code action diagnostics exceed the 512 item limit".into(),
377            ));
378        }
379        let uri = self.sync_document(path)?.uri.clone();
380        self.request_result(
381            "textDocument/codeAction",
382            serde_json::json!({
383                "textDocument":{"uri":uri},
384                "range":{"start":protocol_position(&start),"end":protocol_position(&end)},
385                "context":{"diagnostics":diagnostics}
386            }),
387        )
388    }
389
390    pub fn formatting(&mut self, path: &str) -> DevelopmentResult<LanguageResponse> {
391        let uri = self.sync_document(path)?.uri.clone();
392        self.request_result("textDocument/formatting", serde_json::json!({"textDocument":{"uri":uri},"options":{"tabSize":4,"insertSpaces":true}}))
393    }
394
395    pub fn range_formatting(
396        &mut self,
397        path: &str,
398        start: DiagnosticPosition,
399        end: DiagnosticPosition,
400    ) -> DevelopmentResult<LanguageResponse> {
401        let uri = self.sync_document(path)?.uri.clone();
402        self.request_result(
403            "textDocument/rangeFormatting",
404            serde_json::json!({
405                "textDocument":{"uri":uri},
406                "range":{"start":protocol_position(&start),"end":protocol_position(&end)},
407                "options":{"tabSize":4,"insertSpaces":true}
408            }),
409        )
410    }
411
412    pub fn semantic_tokens(&mut self, path: &str) -> DevelopmentResult<LanguageResponse> {
413        let uri = self.sync_document(path)?.uri.clone();
414        self.request_result(
415            "textDocument/semanticTokens/full",
416            serde_json::json!({"textDocument":{"uri":uri}}),
417        )
418    }
419
420    /// Bounded advanced request escape hatch. Lifecycle and protocol methods
421    /// stay owned by Glass and cannot be overridden by callers.
422    pub fn raw_request(
423        &mut self,
424        method: &str,
425        params: Value,
426        timeout: Duration,
427    ) -> DevelopmentResult<LanguageResponse> {
428        validate_lsp_text("LSP method", method, 256, false)?;
429        if !method.contains('/')
430            || matches!(
431                method,
432                "initialize" | "initialized" | "shutdown" | "exit" | "$/cancelRequest"
433            )
434            || method.starts_with("window/")
435        {
436            return Err(DevelopmentError::InvalidInput(
437                "raw LSP requests cannot control lifecycle or server UI".into(),
438            ));
439        }
440        if timeout.is_zero() || timeout > Duration::from_secs(60) {
441            return Err(DevelopmentError::InvalidInput(
442                "raw LSP timeout must be between 1 ms and 60 seconds".into(),
443            ));
444        }
445        if serde_json::to_vec(&params)?.len() > MAX_LSP_MESSAGE_BYTES {
446            return Err(DevelopmentError::InvalidInput(
447                "raw LSP parameters exceed the size limit".into(),
448            ));
449        }
450        let response = self.call(method, params, timeout)?;
451        if let Some(error) = response.get("error") {
452            return Err(DevelopmentError::Process(format!(
453                "{method} failed: {error}"
454            )));
455        }
456        Ok(LanguageResponse {
457            method: method.into(),
458            result: response.get("result").cloned().unwrap_or(Value::Null),
459        })
460    }
461
462    pub fn rename(
463        &mut self,
464        path: &str,
465        line: u32,
466        character: u32,
467        new_name: &str,
468    ) -> DevelopmentResult<LanguageResponse> {
469        if new_name.is_empty() || new_name.len() > 256 {
470            return Err(DevelopmentError::InvalidInput(
471                "rename target must be 1 to 256 bytes".into(),
472            ));
473        }
474        self.position_request(
475            "textDocument/rename",
476            path,
477            line,
478            character,
479            serde_json::json!({"newName":new_name}),
480        )
481    }
482
483    fn position_request(
484        &mut self,
485        method: &str,
486        path: &str,
487        line: u32,
488        character: u32,
489        extra: Value,
490    ) -> DevelopmentResult<LanguageResponse> {
491        let uri = self.sync_document(path)?.uri.clone();
492        let mut params = serde_json::json!({"textDocument":{"uri":uri},"position":{"line":line.saturating_sub(1),"character":character.saturating_sub(1)}});
493        if let (Some(target), Some(source)) = (params.as_object_mut(), extra.as_object()) {
494            target.extend(source.clone());
495        }
496        self.request_result(method, params)
497    }
498
499    fn request_result(
500        &mut self,
501        method: &str,
502        params: Value,
503    ) -> DevelopmentResult<LanguageResponse> {
504        let response = self.call(method, params, Duration::from_secs(15))?;
505        if let Some(error) = response.get("error") {
506            return Err(DevelopmentError::Process(format!(
507                "{method} failed: {error}"
508            )));
509        }
510        let result = response.get("result").cloned().unwrap_or(Value::Null);
511        if serde_json::to_vec(&result)?.len() > MAX_LSP_MESSAGE_BYTES {
512            return Err(DevelopmentError::Serialization(
513                "language response exceeds the size limit".into(),
514            ));
515        }
516        Ok(LanguageResponse {
517            method: method.into(),
518            result,
519        })
520    }
521
522    fn resolve_document(&self, path: &str) -> DevelopmentResult<(PathBuf, String)> {
523        let relative = Path::new(path);
524        if relative.is_absolute()
525            || relative
526                .components()
527                .any(|part| matches!(part, std::path::Component::ParentDir))
528        {
529            return Err(DevelopmentError::PathOutsideWorkspace(relative.into()));
530        }
531        let absolute = fs::canonicalize(self.root.join(relative))?;
532        if !absolute.starts_with(&self.root) {
533            return Err(DevelopmentError::PathOutsideWorkspace(absolute));
534        }
535        Ok((absolute, relative.to_string_lossy().into_owned()))
536    }
537
538    fn initialize(&mut self) -> DevelopmentResult<()> {
539        let root_uri = file_uri(&self.root)?;
540        let response = self.call(
541            "initialize",
542            serde_json::json!({
543                "processId": std::process::id(),
544                "rootUri": root_uri,
545                "capabilities": {
546                    "workspace": {"workspaceEdit": {"documentChanges": true}},
547                    "textDocument": {
548                        "publishDiagnostics": {"relatedInformation": true},
549                        "completion": {"completionItem": {"snippetSupport": false}},
550                        "signatureHelp": {},
551                        "codeAction": {"dataSupport": true},
552                        "rename": {"prepareSupport": true},
553                        "semanticTokens": {"requests": {"full": true}, "tokenTypes": [], "tokenModifiers": [], "formats": ["relative"]}
554                    }
555                },
556                "workspaceFolders": [{"uri": root_uri, "name": self.root.file_name().and_then(|name| name.to_str()).unwrap_or("project")}]
557            }),
558            Duration::from_secs(30),
559        )?;
560        if response.get("error").is_some() {
561            return Err(DevelopmentError::Process(format!(
562                "language server initialization failed: {}",
563                response["error"]
564            )));
565        }
566        self.notify(serde_json::json!({
567            "jsonrpc": "2.0",
568            "method": "initialized",
569            "params": {}
570        }))
571    }
572
573    fn call(&mut self, method: &str, params: Value, timeout: Duration) -> DevelopmentResult<Value> {
574        let id = self.next_id;
575        self.next_id = self.next_id.saturating_add(1);
576        self.notify(serde_json::json!({
577            "jsonrpc": "2.0",
578            "id": id,
579            "method": method,
580            "params": params
581        }))?;
582        let deadline = Instant::now() + timeout;
583        loop {
584            let value = self
585                .output
586                .recv_timeout(deadline.saturating_duration_since(Instant::now()))
587                .map_err(|error| {
588                    DevelopmentError::Process(format!(
589                        "language server response timed out: {error}"
590                    ))
591                })?;
592            if value.get("id").and_then(Value::as_u64) == Some(id) {
593                return Ok(value);
594            }
595        }
596    }
597
598    fn notify(&mut self, value: Value) -> DevelopmentResult<()> {
599        let body = serde_json::to_vec(&value)?;
600        if body.len() > MAX_LSP_MESSAGE_BYTES {
601            return Err(DevelopmentError::InvalidInput(
602                "language protocol message exceeds the size limit".into(),
603            ));
604        }
605        write!(self.input, "Content-Length: {}\r\n\r\n", body.len())?;
606        self.input.write_all(&body)?;
607        self.input.flush()?;
608        Ok(())
609    }
610}
611
612impl Drop for LspClient {
613    fn drop(&mut self) {
614        if !self.shutdown {
615            let _ = self.call("shutdown", Value::Null, Duration::from_secs(2));
616            self.shutdown = true;
617        }
618        let _ = self.notify(serde_json::json!({
619            "jsonrpc": "2.0",
620            "method": "exit",
621            "params": null
622        }));
623        let _ = self.child.kill();
624        let _ = self.child.wait();
625    }
626}
627
628/// Stable read-only view of an open document's protocol identity.
629#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
630#[serde(rename_all = "camelCase")]
631pub struct LanguageDocument {
632    pub uri: String,
633    pub version: i64,
634}
635
636fn read_lsp_messages(output: impl Read, sender: mpsc::SyncSender<Value>) {
637    let mut reader = BufReader::new(output);
638    loop {
639        let mut content_length = None;
640        loop {
641            let mut header = String::new();
642            match reader.read_line(&mut header) {
643                Ok(0) | Err(_) => return,
644                Ok(_) if header == "\r\n" || header == "\n" => break,
645                Ok(_) => {
646                    if let Some(value) = header
647                        .strip_prefix("Content-Length:")
648                        .and_then(|value| value.trim().parse::<usize>().ok())
649                    {
650                        content_length = Some(value);
651                    }
652                }
653            }
654        }
655        let Some(length) = content_length.filter(|length| *length <= MAX_LSP_MESSAGE_BYTES) else {
656            return;
657        };
658        let mut body = vec![0; length];
659        if reader.read_exact(&mut body).is_err() {
660            return;
661        }
662        if let Ok(value) = serde_json::from_slice(&body)
663            && sender.send(value).is_err()
664        {
665            return;
666        }
667    }
668}
669
670fn parse_diagnostic(path: &str, value: &Value) -> DevelopmentResult<LanguageDiagnostic> {
671    let position = |pointer: &str| -> DevelopmentResult<DiagnosticPosition> {
672        let value = value.pointer(pointer).ok_or_else(|| {
673            DevelopmentError::Serialization(format!("diagnostic is missing {pointer}"))
674        })?;
675        Ok(DiagnosticPosition {
676            line: value.get("line").and_then(Value::as_u64).unwrap_or(0) as u32 + 1,
677            character: value.get("character").and_then(Value::as_u64).unwrap_or(0) as u32 + 1,
678        })
679    };
680    let code = value.get("code").and_then(|code| {
681        code.as_str()
682            .map(str::to_string)
683            .or_else(|| code.as_i64().map(|number| number.to_string()))
684    });
685    Ok(LanguageDiagnostic {
686        path: path.into(),
687        start: position("/range/start")?,
688        end: position("/range/end")?,
689        severity: value
690            .get("severity")
691            .and_then(Value::as_u64)
692            .map(|value| value as u8),
693        code,
694        source: value
695            .get("source")
696            .and_then(Value::as_str)
697            .map(str::to_string),
698        message: value
699            .get("message")
700            .and_then(Value::as_str)
701            .unwrap_or("language diagnostic")
702            .chars()
703            .take(4096)
704            .collect(),
705    })
706}
707
708fn protocol_position(position: &DiagnosticPosition) -> Value {
709    serde_json::json!({
710        "line": position.line.saturating_sub(1),
711        "character": position.character.saturating_sub(1)
712    })
713}
714
715fn validate_lsp_text(
716    description: &str,
717    value: &str,
718    limit: usize,
719    allow_empty: bool,
720) -> DevelopmentResult<()> {
721    if (!allow_empty && value.is_empty())
722        || value.len() > limit
723        || value.chars().any(char::is_control)
724    {
725        return Err(DevelopmentError::InvalidInput(format!(
726            "{description} must contain {}..={limit} non-control bytes",
727            usize::from(!allow_empty)
728        )));
729    }
730    Ok(())
731}
732
733fn file_uri(path: &Path) -> DevelopmentResult<String> {
734    url::Url::from_file_path(path)
735        .map(|url| url.to_string())
736        .map_err(|_| {
737            DevelopmentError::InvalidInput(format!(
738                "cannot represent path as URI: {}",
739                path.display()
740            ))
741        })
742}
743
744fn language_id(path: &Path) -> &'static str {
745    match path.extension().and_then(|extension| extension.to_str()) {
746        Some("rs") => "rust",
747        Some("ts" | "tsx") => "typescript",
748        Some("js" | "jsx") => "javascript",
749        Some("py") => "python",
750        Some("go") => "go",
751        _ => "plaintext",
752    }
753}
754
755#[cfg(test)]
756mod tests {
757    use super::*;
758
759    #[test]
760    fn raw_language_requests_reject_lifecycle_and_unbounded_inputs() {
761        assert!(validate_lsp_text("method", "textDocument/hover", 256, false).is_ok());
762        assert!(validate_lsp_text("method", "", 256, false).is_err());
763        assert!(validate_lsp_text("method", "textDocument\nhover", 256, false).is_err());
764        assert_eq!(
765            protocol_position(&DiagnosticPosition {
766                line: 4,
767                character: 2
768            }),
769            serde_json::json!({"line":3,"character":1})
770        );
771    }
772
773    #[test]
774    fn rust_analyzer_publishes_real_diagnostics_when_available() {
775        if !Command::new("rust-analyzer")
776            .arg("--version")
777            .output()
778            .is_ok_and(|output| output.status.success())
779        {
780            return;
781        }
782        let root = std::env::temp_dir().join(format!("glass-lsp-{}", std::process::id()));
783        let _ = fs::remove_dir_all(&root);
784        fs::create_dir_all(root.join("src")).unwrap();
785        fs::write(
786            root.join("Cargo.toml"),
787            "[package]\nname='glass_lsp_fixture'\nversion='0.1.0'\nedition='2024'\n",
788        )
789        .unwrap();
790        fs::write(root.join("src/lib.rs"), "pub fn broken( {\n").unwrap();
791        let mut client = LspClient::rust_analyzer(&root).unwrap();
792        #[cfg(unix)]
793        let server_pid = client.child.id();
794        assert_eq!(client.sync_document("src/lib.rs").unwrap().version, 1);
795        fs::write(root.join("src/lib.rs"), "pub fn broken( -> u8 {\n").unwrap();
796        assert_eq!(client.sync_document("src/lib.rs").unwrap().version, 2);
797        client.save_document("src/lib.rs").unwrap();
798        let diagnostics = client.diagnostics("src/lib.rs").unwrap();
799        assert!(
800            !diagnostics.is_empty(),
801            "rust-analyzer returned no diagnostics"
802        );
803        assert!(
804            diagnostics
805                .iter()
806                .all(|diagnostic| diagnostic.path == "src/lib.rs")
807        );
808        client.close_document("src/lib.rs").unwrap();
809        drop(client);
810        #[cfg(unix)]
811        {
812            // SAFETY: signal zero performs a read-only existence probe.
813            let result = unsafe { libc::kill(server_pid as i32, 0) };
814            assert_ne!(result, 0, "language server survived client shutdown");
815            assert_eq!(
816                std::io::Error::last_os_error().raw_os_error(),
817                Some(libc::ESRCH)
818            );
819        }
820        let _ = fs::remove_dir_all(root);
821    }
822}