codive-lsp 0.1.0

LSP client infrastructure for Codive
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
//! LSP facade providing high-level API
//!
//! This module provides a high-level interface to LSP operations with
//! lazy initialization, client caching, and automatic server management.

use crate::client::LspClient;
use crate::server::{LspRegistry, LspServerInfo};
use crate::types::*;
use anyhow::{anyhow, Result};
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use tokio::sync::{Mutex, RwLock};
use tracing::{debug, error, info, warn};

/// LSP facade providing high-level operations
pub struct Lsp {
    /// Server registry
    registry: LspRegistry,
    /// Active clients keyed by (root, server_id)
    clients: RwLock<HashMap<(PathBuf, String), Arc<LspClient>>>,
    /// Servers that failed to start (to avoid retrying)
    broken: RwLock<HashSet<(PathBuf, String)>>,
    /// Clients currently being spawned
    spawning: Mutex<HashMap<(PathBuf, String), tokio::sync::broadcast::Sender<()>>>,
    /// Working directory (for relative paths)
    working_dir: PathBuf,
}

impl Lsp {
    /// Create a new LSP facade
    pub fn new(working_dir: PathBuf) -> Self {
        Self {
            registry: LspRegistry::new(),
            clients: RwLock::new(HashMap::new()),
            broken: RwLock::new(HashSet::new()),
            spawning: Mutex::new(HashMap::new()),
            working_dir,
        }
    }

    /// Create with custom registry
    pub fn with_registry(working_dir: PathBuf, registry: LspRegistry) -> Self {
        Self {
            registry,
            clients: RwLock::new(HashMap::new()),
            broken: RwLock::new(HashSet::new()),
            spawning: Mutex::new(HashMap::new()),
            working_dir,
        }
    }

    /// Get the working directory
    pub fn working_dir(&self) -> &Path {
        &self.working_dir
    }

    /// Check if there are any clients available for a file
    pub async fn has_clients(&self, path: &Path) -> bool {
        let path = self.resolve_path(path);
        let ext = path
            .extension()
            .and_then(|e| e.to_str())
            .map(|e| format!(".{}", e))
            .unwrap_or_default();

        for server in self.registry.servers_for_extension(&ext) {
            if let Some(root) = server.detect_root(&path) {
                let key = (root, server.id.clone());
                let broken = self.broken.read().await;
                if !broken.contains(&key) {
                    return true;
                }
            }
        }

        false
    }

    /// Get clients for a file (spawning if necessary)
    pub async fn clients_for_file(&self, path: &Path) -> Result<Vec<Arc<LspClient>>> {
        let path = self.resolve_path(path);
        let ext = path
            .extension()
            .and_then(|e| e.to_str())
            .map(|e| format!(".{}", e))
            .unwrap_or_default();

        let mut result = Vec::new();

        for server in self.registry.servers_for_extension(&ext) {
            if let Some(client) = self.get_or_spawn_client(&path, server).await? {
                result.push(client);
            }
        }

        Ok(result)
    }

    /// Touch a file (notify LSP servers about it)
    pub async fn touch_file(&self, path: &Path, wait_for_diagnostics: bool) -> Result<()> {
        let path = self.resolve_path(path);
        let clients = self.clients_for_file(&path).await?;

        for client in clients {
            if let Err(e) = client.open_file(&path).await {
                warn!(
                    server_id = %client.server_id(),
                    path = ?path,
                    error = ?e,
                    "Failed to open file in LSP"
                );
            }
        }

        // TODO: Implement wait_for_diagnostics if needed
        if wait_for_diagnostics {
            // Give servers a moment to process
            tokio::time::sleep(std::time::Duration::from_millis(100)).await;
        }

        Ok(())
    }

    // ========================================================================
    // LSP Operations
    // ========================================================================

    /// Get hover information
    pub async fn hover(
        &self,
        path: &Path,
        line: u32,
        character: u32,
    ) -> Result<Vec<Option<Hover>>> {
        let path = self.resolve_path(path);
        let path_clone = path.clone();
        self.run_on_file(&path, move |client| {
            let p = path_clone.clone();
            async move { client.hover(&p, line, character).await }
        })
        .await
    }

    /// Go to definition
    pub async fn definition(
        &self,
        path: &Path,
        line: u32,
        character: u32,
    ) -> Result<Vec<Location>> {
        let path = self.resolve_path(path);
        let path_clone = path.clone();
        let results = self
            .run_on_file(&path, move |client| {
                let p = path_clone.clone();
                async move { client.definition(&p, line, character).await }
            })
            .await?;
        Ok(results.into_iter().flatten().collect())
    }

    /// Find references
    pub async fn references(
        &self,
        path: &Path,
        line: u32,
        character: u32,
    ) -> Result<Vec<Location>> {
        let path = self.resolve_path(path);
        let path_clone = path.clone();
        let results = self
            .run_on_file(&path, move |client| {
                let p = path_clone.clone();
                async move { client.references(&p, line, character, true).await }
            })
            .await?;
        Ok(results.into_iter().flatten().collect())
    }

    /// Go to implementation
    pub async fn implementation(
        &self,
        path: &Path,
        line: u32,
        character: u32,
    ) -> Result<Vec<Location>> {
        let path = self.resolve_path(path);
        let path_clone = path.clone();
        let results = self
            .run_on_file(&path, move |client| {
                let p = path_clone.clone();
                async move { client.implementation(&p, line, character).await }
            })
            .await?;
        Ok(results.into_iter().flatten().collect())
    }

    /// Get document symbols
    pub async fn document_symbols(&self, path: &Path) -> Result<Vec<DocumentSymbolResponse>> {
        let path = self.resolve_path(path);
        let path_clone = path.clone();
        self.run_on_file(&path, move |client| {
            let p = path_clone.clone();
            async move { client.document_symbols(&p).await }
        })
        .await
    }

    /// Search workspace symbols
    pub async fn workspace_symbols(&self, query: &str) -> Result<Vec<SymbolInformation>> {
        let clients = self.clients.read().await;
        let mut results = Vec::new();

        for client in clients.values() {
            match client.workspace_symbols(query).await {
                Ok(symbols) => {
                    // Filter to important symbol kinds and limit
                    let filtered: Vec<_> = symbols
                        .into_iter()
                        .filter(|s| IMPORTANT_SYMBOL_KINDS.contains(&s.kind))
                        .take(10)
                        .collect();
                    results.extend(filtered);
                }
                Err(e) => {
                    warn!(
                        server_id = %client.server_id(),
                        error = ?e,
                        "Failed to get workspace symbols"
                    );
                }
            }
        }

        Ok(results)
    }

    /// Prepare call hierarchy
    pub async fn prepare_call_hierarchy(
        &self,
        path: &Path,
        line: u32,
        character: u32,
    ) -> Result<Vec<CallHierarchyItem>> {
        let path = self.resolve_path(path);
        let path_clone = path.clone();
        let results = self
            .run_on_file(&path, move |client| {
                let p = path_clone.clone();
                async move { client.prepare_call_hierarchy(&p, line, character).await }
            })
            .await?;
        Ok(results.into_iter().flatten().collect())
    }

    /// Get incoming calls
    pub async fn incoming_calls(
        &self,
        path: &Path,
        line: u32,
        character: u32,
    ) -> Result<Vec<CallHierarchyIncomingCall>> {
        let path = self.resolve_path(path);
        let items = self.prepare_call_hierarchy(&path, line, character).await?;

        if items.is_empty() {
            return Ok(vec![]);
        }

        // Use the first item
        let item = items.into_iter().next().unwrap();
        let results = self
            .run_on_file(&path, |client| {
                let item = item.clone();
                async move { client.incoming_calls(item).await }
            })
            .await?;
        Ok(results.into_iter().flatten().collect())
    }

    /// Get outgoing calls
    pub async fn outgoing_calls(
        &self,
        path: &Path,
        line: u32,
        character: u32,
    ) -> Result<Vec<CallHierarchyOutgoingCall>> {
        let path = self.resolve_path(path);
        let items = self.prepare_call_hierarchy(&path, line, character).await?;

        if items.is_empty() {
            return Ok(vec![]);
        }

        // Use the first item
        let item = items.into_iter().next().unwrap();
        let results = self
            .run_on_file(&path, |client| {
                let item = item.clone();
                async move { client.outgoing_calls(item).await }
            })
            .await?;
        Ok(results.into_iter().flatten().collect())
    }

    /// Get all diagnostics
    pub async fn diagnostics(&self) -> HashMap<PathBuf, Vec<Diagnostic>> {
        let clients = self.clients.read().await;
        let mut result = HashMap::new();

        for client in clients.values() {
            for (path, diags) in client.diagnostics() {
                result
                    .entry(path)
                    .or_insert_with(Vec::new)
                    .extend(diags);
            }
        }

        result
    }

    /// Get diagnostics for a specific file
    pub async fn diagnostics_for_file(&self, path: &Path) -> Vec<Diagnostic> {
        let path = self.resolve_path(path);
        let clients = self.clients.read().await;
        let mut result = Vec::new();

        for client in clients.values() {
            result.extend(client.diagnostics_for_file(&path));
        }

        result
    }

    /// Get status of all active LSP servers
    pub async fn status(&self) -> Vec<LspStatus> {
        let clients = self.clients.read().await;
        clients
            .values()
            .map(|client| LspStatus {
                id: client.server_id().to_string(),
                name: client.server_id().to_string(),
                root: client
                    .root()
                    .strip_prefix(&self.working_dir)
                    .unwrap_or(client.root())
                    .to_string_lossy()
                    .to_string(),
                status: LspConnectionStatus::Connected,
            })
            .collect()
    }

    /// Shutdown all clients
    pub async fn shutdown(self) {
        info!("Shutting down all LSP clients");
        let clients = self.clients.into_inner();
        for (_, client) in clients {
            if let Ok(client) = Arc::try_unwrap(client) {
                client.shutdown().await;
            }
        }
    }

    // ========================================================================
    // Internal Methods
    // ========================================================================

    /// Resolve a path relative to working directory
    fn resolve_path(&self, path: &Path) -> PathBuf {
        if path.is_absolute() {
            path.to_path_buf()
        } else {
            self.working_dir.join(path)
        }
    }

    /// Get or spawn a client for a file
    async fn get_or_spawn_client(
        &self,
        path: &Path,
        server: &LspServerInfo,
    ) -> Result<Option<Arc<LspClient>>> {
        let root = match server.detect_root(path) {
            Some(root) => root,
            None => return Ok(None),
        };

        let key = (root.clone(), server.id.clone());

        // Check if broken
        {
            let broken = self.broken.read().await;
            if broken.contains(&key) {
                return Ok(None);
            }
        }

        // Check if already exists
        {
            let clients = self.clients.read().await;
            if let Some(client) = clients.get(&key) {
                return Ok(Some(client.clone()));
            }
        }

        // Check if currently spawning
        {
            let spawning = self.spawning.lock().await;
            if let Some(tx) = spawning.get(&key) {
                let mut rx = tx.subscribe();
                drop(spawning);
                let _ = rx.recv().await;

                // Now check if client exists
                let clients = self.clients.read().await;
                return Ok(clients.get(&key).cloned());
            }
        }

        // Spawn the client
        info!(server_id = %server.id, root = ?root, "Spawning LSP server");

        let (tx, _) = tokio::sync::broadcast::channel(1);
        {
            let mut spawning = self.spawning.lock().await;
            spawning.insert(key.clone(), tx.clone());
        }

        let result = self.spawn_client(server, &root).await;

        // Clean up spawning state
        {
            let mut spawning = self.spawning.lock().await;
            spawning.remove(&key);
        }
        let _ = tx.send(());

        match result {
            Ok(client) => {
                let client = Arc::new(client);
                let mut clients = self.clients.write().await;
                clients.insert(key, client.clone());
                Ok(Some(client))
            }
            Err(e) => {
                error!(
                    server_id = %server.id,
                    root = ?root,
                    error = ?e,
                    "Failed to spawn LSP server"
                );
                let mut broken = self.broken.write().await;
                broken.insert(key);
                Ok(None)
            }
        }
    }

    /// Spawn a new client
    async fn spawn_client(&self, server: &LspServerInfo, root: &Path) -> Result<LspClient> {
        let handle = server.spawn(root)?;
        LspClient::new(&server.id, handle, root.to_path_buf()).await
    }

    /// Run an operation on all clients for a file
    async fn run_on_file<F, Fut, T>(&self, path: &Path, f: F) -> Result<Vec<T>>
    where
        F: Fn(Arc<LspClient>) -> Fut,
        Fut: std::future::Future<Output = Result<T>>,
    {
        let clients = self.clients_for_file(path).await?;

        // Touch the file first
        for client in &clients {
            if let Err(e) = client.open_file(path).await {
                warn!(
                    server_id = %client.server_id(),
                    path = ?path,
                    error = ?e,
                    "Failed to open file"
                );
            }
        }

        let mut results = Vec::new();
        for client in clients {
            match f(client.clone()).await {
                Ok(result) => results.push(result),
                Err(e) => {
                    warn!(
                        server_id = %client.server_id(),
                        error = ?e,
                        "LSP operation failed"
                    );
                }
            }
        }

        Ok(results)
    }
}

// ============================================================================
// Global Instance
// ============================================================================

use std::sync::OnceLock;

static LSP_INSTANCE: OnceLock<Lsp> = OnceLock::new();

/// Initialize the global LSP instance
pub fn init(working_dir: PathBuf) -> &'static Lsp {
    LSP_INSTANCE.get_or_init(|| Lsp::new(working_dir))
}

/// Get the global LSP instance
pub fn lsp() -> Option<&'static Lsp> {
    LSP_INSTANCE.get()
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::tempdir;

    #[tokio::test]
    async fn test_lsp_new() {
        let temp = tempdir().unwrap();
        let lsp = Lsp::new(temp.path().to_path_buf());
        assert_eq!(lsp.working_dir(), temp.path());
    }

    #[tokio::test]
    async fn test_has_clients_no_root() {
        let temp = tempdir().unwrap();
        let lsp = Lsp::new(temp.path().to_path_buf());

        // File without a project root
        let file = temp.path().join("orphan.rs");
        std::fs::write(&file, "fn main() {}").unwrap();

        assert!(!lsp.has_clients(&file).await);
    }

    #[tokio::test]
    async fn test_status_empty() {
        let temp = tempdir().unwrap();
        let lsp = Lsp::new(temp.path().to_path_buf());

        let status = lsp.status().await;
        assert!(status.is_empty());
    }
}