1use anyhow::{Context, Result};
7use lsp_types::{Diagnostic, DiagnosticSeverity, InitializeParams, InitializeResult};
8use serde::Deserialize;
9use serde_json::{Value, json};
10use std::collections::HashMap;
11use std::path::Path;
12use std::process::Stdio;
13use std::sync::Arc;
14use std::sync::atomic::{AtomicU64, Ordering};
15use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
16use tokio::process::{Child, ChildStdin, Command};
17use tokio::sync::{Mutex, oneshot};
18
19use perspt_core::plugin::LspConfig;
20use perspt_sandbox::{ProcessPolicy, ProcessSandbox};
21
22type PendingRequests = Arc<Mutex<HashMap<u64, oneshot::Sender<Result<Value>>>>>;
24type DiagnosticsMap = Arc<Mutex<HashMap<String, Vec<Diagnostic>>>>;
26
27#[derive(Debug, Clone)]
29pub struct DocumentSymbolInfo {
30 pub name: String,
32 pub kind: String,
34 pub range: lsp_types::Range,
36 pub detail: Option<String>,
38}
39
40pub struct LspClient {
42 stdin: Option<Arc<Mutex<ChildStdin>>>,
44 request_id: AtomicU64,
46 pending_requests: Arc<Mutex<HashMap<u64, oneshot::Sender<Result<Value>>>>>,
48 diagnostics: Arc<Mutex<HashMap<String, Vec<Diagnostic>>>>,
50 server_name: String,
52 language_id: String,
54 process: Option<Child>,
56 initialized: bool,
58 allow_unisolated: bool,
60}
61
62impl LspClient {
63 pub fn new(server_name: &str) -> Self {
65 Self {
66 stdin: None,
67 request_id: AtomicU64::new(1),
68 pending_requests: Arc::new(Mutex::new(HashMap::new())),
69 diagnostics: Arc::new(Mutex::new(HashMap::new())),
70 server_name: server_name.to_string(),
71 language_id: String::new(),
72 process: None,
73 initialized: false,
74 allow_unisolated: false,
75 }
76 }
77
78 pub fn from_config(config: &LspConfig) -> Self {
83 Self {
84 stdin: None,
85 request_id: AtomicU64::new(1),
86 pending_requests: Arc::new(Mutex::new(HashMap::new())),
87 diagnostics: Arc::new(Mutex::new(HashMap::new())),
88 server_name: config.server_binary.clone(),
89 language_id: config.language_id.clone(),
90 process: None,
91 initialized: false,
92 allow_unisolated: false,
93 }
94 }
95
96 pub(crate) fn allow_unisolated(mut self, allow: bool) -> Self {
97 self.allow_unisolated = allow;
98 self
99 }
100
101 fn get_server_command(server_name: &str) -> Option<(&'static str, Vec<&'static str>)> {
103 match server_name {
104 "rust-analyzer" => Some(("rust-analyzer", vec![])),
105 "pyright" => Some(("pyright-langserver", vec!["--stdio"])),
106 "ty" => Some(("uvx", vec!["ty", "server"])),
108 "typescript" => Some(("typescript-language-server", vec!["--stdio"])),
109 "gopls" => Some(("gopls", vec!["serve"])),
110 _ => None,
111 }
112 }
113
114 pub async fn start(&mut self, workspace_root: &Path) -> Result<()> {
116 let (cmd, args) = Self::get_server_command(&self.server_name)
117 .context(format!("Unknown language server: {}", self.server_name))?;
118
119 let args_owned: Vec<String> = args.iter().map(|s| s.to_string()).collect();
120 self.start_process(cmd, &args_owned, workspace_root).await
121 }
122
123 pub async fn start_with_config(
128 &mut self,
129 config: &LspConfig,
130 workspace_root: &Path,
131 ) -> Result<()> {
132 self.start_process(&config.server_binary, &config.args, workspace_root)
133 .await
134 }
135
136 async fn start_process(
138 &mut self,
139 cmd: &str,
140 args: &[String],
141 workspace_root: &Path,
142 ) -> Result<()> {
143 log::info!("Starting LSP server: {} {:?}", cmd, args);
144
145 let policy = if self.allow_unisolated {
146 ProcessPolicy::inspection(workspace_root).best_effort()
147 } else {
148 ProcessPolicy::inspection(workspace_root)
149 };
150 let prepared = ProcessSandbox::new(cmd, args.to_vec(), policy)?.prepare_invocation()?;
151 let mut child = Command::new(&prepared.program);
152 child
153 .args(&prepared.args)
154 .current_dir(&prepared.working_dir)
155 .env_clear()
156 .envs(&prepared.environment)
157 .stdin(Stdio::piped())
158 .stdout(Stdio::piped())
159 .stderr(Stdio::piped());
160 let mut child = child.spawn().context(format!("Failed to start {}", cmd))?;
161
162 let stdin = child.stdin.take().context("No stdin")?;
163 let stdout = child.stdout.take().context("No stdout")?;
164 let stderr = child.stderr.take().context("No stderr")?;
165
166 tokio::spawn(async move {
168 let mut reader = BufReader::new(stderr).lines();
169 while let Ok(Some(line)) = reader.next_line().await {
170 log::debug!("[LSP stderr] {}", line);
171 }
172 });
173
174 let pending_requests = self.pending_requests.clone();
176 let diagnostics = self.diagnostics.clone();
177
178 tokio::spawn(async move {
179 let mut reader = BufReader::new(stdout);
180 loop {
181 let mut content_length = 0;
183 loop {
184 let mut line = String::new();
185 match reader.read_line(&mut line).await {
186 Ok(0) => return, Ok(_) => {
188 if line == "\r\n" {
189 break;
190 }
191 if line.starts_with("Content-Length:")
192 && let Ok(len) = line
193 .trim_start_matches("Content-Length:")
194 .trim()
195 .parse::<usize>()
196 {
197 content_length = len;
198 }
199 }
200 Err(e) => {
201 log::error!("Error reading LSP header: {}", e);
202 return;
203 }
204 }
205 }
206
207 if content_length == 0 {
208 continue;
209 }
210
211 let mut body = vec![0u8; content_length];
213 match reader.read_exact(&mut body).await {
214 Ok(_) => {
215 if let Ok(value) = serde_json::from_slice::<Value>(&body) {
216 Self::handle_message(value, &pending_requests, &diagnostics).await;
217 }
218 }
219 Err(e) => {
220 log::error!("Error reading LSP body: {}", e);
221 return;
222 }
223 }
224 }
225 });
226
227 self.stdin = Some(Arc::new(Mutex::new(stdin)));
228 self.process = Some(child);
229 self.initialized = false;
230
231 self.initialize(workspace_root).await?;
233
234 Ok(())
235 }
236
237 async fn handle_message(
239 msg: Value,
240 pending_requests: &PendingRequests,
241 diagnostics: &DiagnosticsMap,
242 ) {
243 if let Some(id) = msg.get("id").and_then(|id| id.as_u64()) {
244 let mut pending = pending_requests.lock().await;
246 if let Some(tx) = pending.remove(&id) {
247 if let Some(error) = msg.get("error") {
248 let _ = tx.send(Err(anyhow::anyhow!("LSP error: {}", error)));
249 } else if let Some(result) = msg.get("result") {
250 let _ = tx.send(Ok(result.clone()));
251 } else {
252 let _ = tx.send(Ok(Value::Null));
253 }
254 }
255 } else if let Some(method) = msg.get("method").and_then(|m| m.as_str()) {
256 if method == "textDocument/publishDiagnostics"
258 && let Some(params) = msg.get("params")
259 && let (Some(uri), Some(diags)) = (
260 params.get("uri").and_then(|u| u.as_str()),
261 params
262 .get("diagnostics")
263 .and_then(|d| serde_json::from_value::<Vec<Diagnostic>>(d.clone()).ok()),
264 )
265 {
266 let path = uri.trim_start_matches("file://");
268
269 let mut diag_map = diagnostics.lock().await;
272
273 if let Some(filename) = Path::new(path).file_name() {
276 let filename_str = filename.to_string_lossy().to_string();
277 diag_map.insert(filename_str, diags.clone());
278 }
279
280 diag_map.insert(path.to_string(), diags);
281 log::info!("Updated diagnostics for {}", path);
282 }
283 }
284 }
285
286 #[allow(deprecated)]
288 async fn initialize(&mut self, workspace_root: &Path) -> Result<InitializeResult> {
289 let path_str = workspace_root.to_string_lossy();
291 #[cfg(target_os = "windows")]
292 let uri_string = format!("file:///{}", path_str.replace('\\', "/"));
293 #[cfg(not(target_os = "windows"))]
294 let uri_string = format!("file://{}", path_str);
295
296 let root_uri: lsp_types::Uri = uri_string
297 .parse()
298 .map_err(|e| anyhow::anyhow!("Failed to parse URI: {:?}", e))?;
299
300 let params = InitializeParams {
301 root_uri: Some(root_uri),
302 capabilities: lsp_types::ClientCapabilities::default(),
303 ..Default::default()
304 };
305
306 let result: InitializeResult = self
307 .send_request("initialize", serde_json::to_value(params)?)
308 .await?;
309
310 self.send_notification("initialized", json!({})).await?;
312 self.initialized = true;
313
314 log::info!("LSP server initialized: {:?}", result.server_info);
315 Ok(result)
316 }
317
318 async fn send_request<T: for<'de> Deserialize<'de>>(
320 &mut self,
321 method: &str,
322 params: Value,
323 ) -> Result<T> {
324 let id = self.request_id.fetch_add(1, Ordering::SeqCst);
325 let (tx, rx) = oneshot::channel();
326
327 {
329 let mut pending = self.pending_requests.lock().await;
330 pending.insert(id, tx);
331 }
332
333 let request = json!({
334 "jsonrpc": "2.0",
335 "id": id,
336 "method": method,
337 "params": params
338 });
339
340 if let Err(e) = self.write_message(&request).await {
341 let mut pending = self.pending_requests.lock().await;
343 pending.remove(&id);
344 return Err(e);
345 }
346
347 let result = rx.await??;
349 Ok(serde_json::from_value(result)?)
350 }
351
352 async fn send_notification(&mut self, method: &str, params: Value) -> Result<()> {
354 let notification = json!({
355 "jsonrpc": "2.0",
356 "method": method,
357 "params": params
358 });
359
360 self.write_message(¬ification).await
361 }
362
363 async fn write_message(&mut self, msg: &Value) -> Result<()> {
365 let content = serde_json::to_string(msg)?;
366 let message = format!("Content-Length: {}\r\n\r\n{}", content.len(), content);
367
368 if let Some(ref stdin_arc) = self.stdin {
369 let mut stdin = stdin_arc.lock().await;
370 stdin.write_all(message.as_bytes()).await?;
371 stdin.flush().await?;
372 Ok(())
373 } else {
374 Err(anyhow::anyhow!("LSP stdin not available"))
375 }
376 }
377
378 pub async fn get_diagnostics(&self, path: &str) -> Vec<Diagnostic> {
381 let map = self.diagnostics.lock().await;
382
383 let mut cached = Vec::new();
385
386 if let Some(diags) = map.get(path) {
388 cached = diags.clone();
389 }
390 else if let Some(diags) = map.get(path.trim_start_matches("file://")) {
392 cached = diags.clone();
393 }
394 else if !path.starts_with("file://") {
396 let uri = format!("file://{}", path);
397 if let Some(diags) = map.get(&uri) {
398 cached = diags.clone();
399 }
400 }
401
402 if cached.is_empty()
404 && let Some(filename) = Path::new(path).file_name()
405 {
406 let filename_str = filename.to_string_lossy();
407 if let Some(diags) = map.get(filename_str.as_ref()) {
408 cached = diags.clone();
409 }
410 }
411
412 if !cached.is_empty() {
416 return cached;
417 }
418
419 if self.server_name == "ty" {
423 drop(map);
425 return self.run_type_check(path).await;
426 }
427
428 Vec::new()
429 }
430
431 async fn run_type_check(&self, path: &str) -> Vec<Diagnostic> {
433 use std::process::Command;
434
435 log::debug!("Running ty check on: {}", path);
436
437 let output = Command::new("uvx").args(["ty", "check", path]).output();
439
440 match output {
441 Ok(output) => {
442 let stdout = String::from_utf8_lossy(&output.stdout);
443 let stderr = String::from_utf8_lossy(&output.stderr);
444
445 log::debug!("ty check status: {}", output.status);
446 if !stdout.is_empty() {
447 log::debug!("ty check stdout: {}", stdout);
448 }
449 if !stderr.is_empty() {
450 log::debug!("ty check stderr: {}", stderr);
451 }
452
453 let combined = format!("{}\n{}", stdout, stderr);
455 self.parse_ty_output(&combined, path)
456 }
457 Err(e) => {
458 log::warn!("Failed to run ty check: {}", e);
459 Vec::new()
460 }
461 }
462 }
463
464 fn parse_ty_output(&self, output: &str, _path: &str) -> Vec<Diagnostic> {
466 let mut diagnostics = Vec::new();
467
468 let lines: Vec<&str> = output.lines().collect();
473 let mut i = 0;
474
475 while i < lines.len() {
476 let line = lines[i];
477
478 if line.contains("error") || line.contains("warning") {
480 let severity = if line.contains("error") {
482 Some(DiagnosticSeverity::ERROR)
483 } else if line.contains("warning") {
484 Some(DiagnosticSeverity::WARNING)
485 } else {
486 Some(DiagnosticSeverity::INFORMATION)
487 };
488
489 let message = if let Some(idx) = line.find("]: ") {
492 line[idx + 3..].to_string()
493 } else if let Some(idx) = line.find(": ") {
494 line[idx + 2..].to_string()
495 } else {
496 line.to_string()
497 };
498
499 let mut line_num = 0;
501 let mut col_num = 0;
502
503 for j in 1..4 {
505 if i + j < lines.len() {
506 let next_line = lines[i + j];
507 if next_line.trim().starts_with("-->") {
508 if let Some(parts) = next_line.split("-->").nth(1) {
511 let parts: Vec<&str> = parts.trim().split(':').collect();
512 if parts.len() >= 3 {
513 line_num = parts[1].parse().unwrap_or(0);
515 col_num = parts[2].parse().unwrap_or(0);
516 }
517 }
518 break;
519 }
520 }
521 }
522
523 diagnostics.push(Diagnostic {
524 range: lsp_types::Range {
525 start: lsp_types::Position {
526 line: if line_num > 0 { line_num - 1 } else { 0 },
527 character: if col_num > 0 { col_num - 1 } else { 0 },
528 },
529 end: lsp_types::Position {
530 line: if line_num > 0 { line_num - 1 } else { 0 },
531 character: if col_num > 0 { col_num } else { 1 },
532 },
533 },
534 severity,
535 message,
536 ..Default::default()
537 });
538 }
539
540 i += 1;
541 }
542
543 if !diagnostics.is_empty() {
544 log::info!("ty check found {} diagnostics", diagnostics.len());
545 }
546
547 diagnostics
548 }
549
550 pub fn calculate_syntactic_energy(diagnostics: &[Diagnostic]) -> f32 {
555 diagnostics
556 .iter()
557 .map(|d| match d.severity {
558 Some(DiagnosticSeverity::ERROR) => 1.0,
559 Some(DiagnosticSeverity::WARNING) => 0.1,
560 Some(DiagnosticSeverity::INFORMATION) => 0.01,
561 Some(DiagnosticSeverity::HINT) => 0.001,
562 _ => 0.1, })
564 .sum()
565 }
566
567 pub fn is_ready(&self) -> bool {
569 self.initialized && self.process.is_some()
570 }
571
572 pub async fn did_open(&mut self, path: &std::path::Path, content: &str) -> Result<()> {
574 if !self.is_ready() {
575 return Ok(());
576 }
577
578 let uri = format!("file://{}", path.display());
579
580 let language_id = if !self.language_id.is_empty() {
582 self.language_id.as_str()
583 } else {
584 match path.extension().and_then(|e| e.to_str()) {
585 Some("py") => "python",
586 Some("rs") => "rust",
587 Some("js") => "javascript",
588 Some("ts") => "typescript",
589 Some("go") => "go",
590 _ => "plaintext",
591 }
592 };
593
594 self.send_notification(
595 "textDocument/didOpen",
596 json!({
597 "textDocument": {
598 "uri": uri,
599 "languageId": language_id,
600 "version": 1,
601 "text": content
602 }
603 }),
604 )
605 .await
606 }
607
608 pub async fn did_change(
610 &mut self,
611 path: &std::path::Path,
612 content: &str,
613 version: i32,
614 ) -> Result<()> {
615 if !self.is_ready() {
616 return Ok(());
617 }
618
619 let uri = format!("file://{}", path.display());
620
621 self.send_notification(
622 "textDocument/didChange",
623 json!({
624 "textDocument": {
625 "uri": uri,
626 "version": version
627 },
628 "contentChanges": [{
629 "text": content
630 }]
631 }),
632 )
633 .await
634 }
635
636 pub async fn goto_definition(
643 &mut self,
644 path: &Path,
645 line: u32,
646 character: u32,
647 ) -> Option<Vec<lsp_types::Location>> {
648 if !self.is_ready() {
649 return None;
650 }
651
652 let uri = format!("file://{}", path.display());
653
654 let params = json!({
655 "textDocument": { "uri": uri },
656 "position": { "line": line, "character": character }
657 });
658
659 match self
660 .send_request::<Option<lsp_types::GotoDefinitionResponse>>(
661 "textDocument/definition",
662 params,
663 )
664 .await
665 {
666 Ok(Some(response)) => {
667 match response {
669 lsp_types::GotoDefinitionResponse::Scalar(loc) => Some(vec![loc]),
670 lsp_types::GotoDefinitionResponse::Array(locs) => Some(locs),
671 lsp_types::GotoDefinitionResponse::Link(links) => Some(
672 links
673 .into_iter()
674 .map(|l| lsp_types::Location {
675 uri: l.target_uri,
676 range: l.target_selection_range,
677 })
678 .collect(),
679 ),
680 }
681 }
682 Ok(None) => None,
683 Err(e) => {
684 log::warn!("goto_definition failed: {}", e);
685 None
686 }
687 }
688 }
689
690 pub async fn find_references(
693 &mut self,
694 path: &Path,
695 line: u32,
696 character: u32,
697 include_declaration: bool,
698 ) -> Vec<lsp_types::Location> {
699 if !self.is_ready() {
700 return Vec::new();
701 }
702
703 let uri = format!("file://{}", path.display());
704
705 let params = json!({
706 "textDocument": { "uri": uri },
707 "position": { "line": line, "character": character },
708 "context": { "includeDeclaration": include_declaration }
709 });
710
711 match self
712 .send_request::<Option<Vec<lsp_types::Location>>>("textDocument/references", params)
713 .await
714 {
715 Ok(Some(locs)) => locs,
716 Ok(None) => Vec::new(),
717 Err(e) => {
718 log::warn!("find_references failed: {}", e);
719 Vec::new()
720 }
721 }
722 }
723
724 pub async fn hover(&mut self, path: &Path, line: u32, character: u32) -> Option<String> {
727 if !self.is_ready() {
728 return None;
729 }
730
731 let uri = format!("file://{}", path.display());
732
733 let params = json!({
734 "textDocument": { "uri": uri },
735 "position": { "line": line, "character": character }
736 });
737
738 match self
739 .send_request::<Option<lsp_types::Hover>>("textDocument/hover", params)
740 .await
741 {
742 Ok(Some(hover)) => {
743 match hover.contents {
745 lsp_types::HoverContents::Scalar(content) => {
746 Some(Self::extract_marked_string(&content))
747 }
748 lsp_types::HoverContents::Array(contents) => Some(
749 contents
750 .iter()
751 .map(Self::extract_marked_string)
752 .collect::<Vec<_>>()
753 .join("\n"),
754 ),
755 lsp_types::HoverContents::Markup(markup) => Some(markup.value),
756 }
757 }
758 Ok(None) => None,
759 Err(e) => {
760 log::warn!("hover failed: {}", e);
761 None
762 }
763 }
764 }
765
766 fn extract_marked_string(content: &lsp_types::MarkedString) -> String {
768 match content {
769 lsp_types::MarkedString::String(s) => s.clone(),
770 lsp_types::MarkedString::LanguageString(ls) => {
771 format!("```{}\n{}\n```", ls.language, ls.value)
772 }
773 }
774 }
775
776 pub async fn get_symbols(&mut self, path: &Path) -> Vec<DocumentSymbolInfo> {
779 if !self.is_ready() {
780 return Vec::new();
781 }
782
783 let uri = format!("file://{}", path.display());
784
785 let params = json!({
786 "textDocument": { "uri": uri }
787 });
788
789 match self
790 .send_request::<Option<lsp_types::DocumentSymbolResponse>>(
791 "textDocument/documentSymbol",
792 params,
793 )
794 .await
795 {
796 Ok(Some(response)) => match response {
797 lsp_types::DocumentSymbolResponse::Flat(symbols) => symbols
798 .into_iter()
799 .map(|s| DocumentSymbolInfo {
800 name: s.name,
801 kind: format!("{:?}", s.kind),
802 range: s.location.range,
803 detail: None,
804 })
805 .collect(),
806 lsp_types::DocumentSymbolResponse::Nested(symbols) => {
807 Self::flatten_document_symbols(&symbols)
808 }
809 },
810 Ok(None) => Vec::new(),
811 Err(e) => {
812 log::warn!("get_symbols failed: {}", e);
813 Vec::new()
814 }
815 }
816 }
817
818 fn flatten_document_symbols(symbols: &[lsp_types::DocumentSymbol]) -> Vec<DocumentSymbolInfo> {
820 let mut result = Vec::new();
821 for sym in symbols {
822 result.push(DocumentSymbolInfo {
823 name: sym.name.clone(),
824 kind: format!("{:?}", sym.kind),
825 range: sym.range,
826 detail: sym.detail.clone(),
827 });
828 if let Some(ref children) = sym.children {
830 result.extend(Self::flatten_document_symbols(children));
831 }
832 }
833 result
834 }
835
836 pub async fn shutdown(&mut self) -> Result<()> {
838 if let Some(ref mut process) = self.process {
839 let _ = process.kill().await;
840 }
841 self.process = None;
842 self.initialized = false;
843 Ok(())
844 }
845}
846
847impl Drop for LspClient {
848 fn drop(&mut self) {
849 if let Some(ref mut process) = self.process {
850 let _ = process.start_kill();
851 }
852 }
853}
854
855#[cfg(test)]
856mod tests {
857 use super::*;
858 use lsp_types::Range;
859
860 #[test]
861 fn test_syntactic_energy_calculation() {
862 let diagnostics = vec![
863 Diagnostic {
864 range: Range::default(),
865 severity: Some(DiagnosticSeverity::ERROR),
866 message: "error".to_string(),
867 ..Default::default()
868 },
869 Diagnostic {
870 range: Range::default(),
871 severity: Some(DiagnosticSeverity::WARNING),
872 message: "warning".to_string(),
873 ..Default::default()
874 },
875 ];
876
877 let energy = LspClient::calculate_syntactic_energy(&diagnostics);
878 assert!((energy - 1.1).abs() < 0.001);
879 }
880}