coderlib 0.1.0

A Rust library for AI-powered code assistance and agentic system
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
//! LSP client implementation

use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::sync::Arc;
use tokio::process::{Child, Command};
use tokio::sync::RwLock;
use url::Url;

use super::config::LspServerConfig;
use super::types::{
    LspError, LspDiagnostic, Position, Range, Location,
    CompletionItem, Hover, CodeAction, SymbolInformation
};
use super::LspService;
use async_trait::async_trait;

/// LSP client for communicating with a language server
pub struct LspClient {
    config: LspServerConfig,
    process: Option<Child>,
    diagnostics: Arc<RwLock<HashMap<PathBuf, Vec<LspDiagnostic>>>>,
    open_files: Arc<RwLock<HashMap<PathBuf, String>>>,
    initialized: Arc<RwLock<bool>>,
    workspace_root: Option<PathBuf>,
}

impl LspClient {
    /// Create a new LSP client
    pub fn new(config: LspServerConfig) -> Self {
        Self {
            config,
            process: None,
            diagnostics: Arc::new(RwLock::new(HashMap::new())),
            open_files: Arc::new(RwLock::new(HashMap::new())),
            initialized: Arc::new(RwLock::new(false)),
            workspace_root: None,
        }
    }
    
    /// Start the LSP server process
    pub async fn start(&mut self, workspace_root: Option<PathBuf>) -> Result<(), LspError> {
        if self.process.is_some() {
            return Ok(()); // Already started
        }
        
        self.workspace_root = workspace_root;
        
        // Start the LSP server process
        let mut cmd = Command::new(&self.config.command);
        cmd.args(&self.config.args);
        cmd.stdin(Stdio::piped());
        cmd.stdout(Stdio::piped());
        cmd.stderr(Stdio::piped());
        
        // Set environment variables
        for (key, value) in &self.config.env {
            cmd.env(key, value);
        }
        
        let child = cmd.spawn()
            .map_err(|e| LspError::ServerStartFailed(format!("Failed to start {}: {}", self.config.command, e)))?;
        
        self.process = Some(child);
        
        // Initialize the LSP server
        self.initialize().await?;
        
        Ok(())
    }
    
    /// Initialize the LSP server
    async fn initialize(&mut self) -> Result<(), LspError> {
        // For now, we'll implement a basic initialization
        // In a full implementation, this would send the initialize request
        // and handle the response properly
        
        let mut initialized = self.initialized.write().await;
        *initialized = true;
        
        tracing::info!("LSP server {} initialized", self.config.name);
        Ok(())
    }
    
    /// Stop the LSP server
    pub async fn stop(&mut self) -> Result<(), LspError> {
        if let Some(mut process) = self.process.take() {
            // Send shutdown request first (in a full implementation)
            
            // Kill the process
            if let Err(e) = process.kill().await {
                tracing::warn!("Failed to kill LSP process: {}", e);
            }
        }
        
        let mut initialized = self.initialized.write().await;
        *initialized = false;
        
        Ok(())
    }
    
    /// Check if the client is initialized
    pub async fn is_initialized(&self) -> bool {
        *self.initialized.read().await
    }
    
    /// Notify the server that a file was opened
    pub async fn did_open(&self, file_path: &Path, content: &str) -> Result<(), LspError> {
        if !self.is_initialized().await {
            return Err(LspError::NotInitialized);
        }
        
        // Store the file content
        let mut open_files = self.open_files.write().await;
        open_files.insert(file_path.to_path_buf(), content.to_string());
        
        // In a full implementation, this would send a textDocument/didOpen notification
        tracing::debug!("File opened: {}", file_path.display());
        
        Ok(())
    }
    
    /// Notify the server that a file was changed
    pub async fn did_change(&self, file_path: &Path, content: &str) -> Result<(), LspError> {
        if !self.is_initialized().await {
            return Err(LspError::NotInitialized);
        }
        
        // Update the file content
        let mut open_files = self.open_files.write().await;
        open_files.insert(file_path.to_path_buf(), content.to_string());
        
        // In a full implementation, this would send a textDocument/didChange notification
        tracing::debug!("File changed: {}", file_path.display());
        
        Ok(())
    }
    
    /// Notify the server that a file was closed
    pub async fn did_close(&self, file_path: &Path) -> Result<(), LspError> {
        if !self.is_initialized().await {
            return Err(LspError::NotInitialized);
        }
        
        // Remove the file from open files
        let mut open_files = self.open_files.write().await;
        open_files.remove(file_path);
        
        // Remove diagnostics for this file
        let mut diagnostics = self.diagnostics.write().await;
        diagnostics.remove(file_path);
        
        // In a full implementation, this would send a textDocument/didClose notification
        tracing::debug!("File closed: {}", file_path.display());
        
        Ok(())
    }
    
    /// Get diagnostics for a file
    pub async fn get_diagnostics(&self, file_path: &Path) -> Result<Vec<LspDiagnostic>, LspError> {
        let diagnostics = self.diagnostics.read().await;
        Ok(diagnostics.get(file_path).cloned().unwrap_or_default())
    }
    
    /// Get all diagnostics
    pub async fn get_all_diagnostics(&self) -> Result<Vec<LspDiagnostic>, LspError> {
        let diagnostics = self.diagnostics.read().await;
        let mut all_diagnostics = Vec::new();
        
        for diags in diagnostics.values() {
            all_diagnostics.extend(diags.clone());
        }
        
        Ok(all_diagnostics)
    }
    
    /// Check if this client handles the given file
    pub fn handles_file(&self, file_path: &Path) -> bool {
        self.config.handles_file(file_path)
    }
    
    /// Get the server configuration
    pub fn config(&self) -> &LspServerConfig {
        &self.config
    }
    
    /// Get code completions at a position
    pub async fn get_completions(&self, file_path: &Path, position: Position) -> Result<Vec<CompletionItem>, LspError> {
        if !self.is_initialized().await {
            return Err(LspError::NotInitialized);
        }

        // In a full implementation, this would send a textDocument/completion request
        tracing::debug!("Getting completions for {} at {}:{}", file_path.display(), position.line, position.character);

        // For now, return empty completions
        // TODO: Implement actual LSP completion request
        Ok(Vec::new())
    }

    /// Go to definition of symbol at position
    pub async fn goto_definition(&self, file_path: &Path, position: Position) -> Result<Vec<Location>, LspError> {
        if !self.is_initialized().await {
            return Err(LspError::NotInitialized);
        }

        // In a full implementation, this would send a textDocument/definition request
        tracing::debug!("Going to definition for {} at {}:{}", file_path.display(), position.line, position.character);

        // For now, return empty locations
        // TODO: Implement actual LSP definition request
        Ok(Vec::new())
    }

    /// Get hover information at position
    pub async fn get_hover(&self, file_path: &Path, position: Position) -> Result<Option<Hover>, LspError> {
        if !self.is_initialized().await {
            return Err(LspError::NotInitialized);
        }

        // In a full implementation, this would send a textDocument/hover request
        tracing::debug!("Getting hover for {} at {}:{}", file_path.display(), position.line, position.character);

        // For now, return no hover information
        // TODO: Implement actual LSP hover request
        Ok(None)
    }

    /// Find references to symbol at position
    pub async fn find_references(&self, file_path: &Path, position: Position, include_declaration: bool) -> Result<Vec<Location>, LspError> {
        if !self.is_initialized().await {
            return Err(LspError::NotInitialized);
        }

        // In a full implementation, this would send a textDocument/references request
        tracing::debug!("Finding references for {} at {}:{} (include_declaration: {})",
                       file_path.display(), position.line, position.character, include_declaration);

        // For now, return empty locations
        // TODO: Implement actual LSP references request
        Ok(Vec::new())
    }

    /// Get code actions for a range
    pub async fn get_code_actions(&self, file_path: &Path, range: Range) -> Result<Vec<CodeAction>, LspError> {
        if !self.is_initialized().await {
            return Err(LspError::NotInitialized);
        }

        // In a full implementation, this would send a textDocument/codeAction request
        tracing::debug!("Getting code actions for {} at {}:{} to {}:{}",
                       file_path.display(), range.start.line, range.start.character,
                       range.end.line, range.end.character);

        // For now, return empty code actions
        // TODO: Implement actual LSP code action request
        Ok(Vec::new())
    }

    /// Get document symbols
    pub async fn get_document_symbols(&self, file_path: &Path) -> Result<Vec<SymbolInformation>, LspError> {
        if !self.is_initialized().await {
            return Err(LspError::NotInitialized);
        }

        // In a full implementation, this would send a textDocument/documentSymbol request
        tracing::debug!("Getting document symbols for {}", file_path.display());

        // For now, return empty symbols
        // TODO: Implement actual LSP document symbols request
        Ok(Vec::new())
    }

    /// Format document
    pub async fn format_document(&self, file_path: &Path) -> Result<String, LspError> {
        if !self.is_initialized().await {
            return Err(LspError::NotInitialized);
        }

        // In a full implementation, this would send a textDocument/formatting request
        tracing::debug!("Formatting document {}", file_path.display());

        // For now, return the original content
        let open_files = self.open_files.read().await;
        if let Some(content) = open_files.get(file_path) {
            Ok(content.clone())
        } else {
            Err(LspError::FileNotOpen(file_path.to_path_buf()))
        }
    }

    /// Format range in document
    pub async fn format_range(&self, file_path: &Path, range: Range) -> Result<String, LspError> {
        if !self.is_initialized().await {
            return Err(LspError::NotInitialized);
        }

        // In a full implementation, this would send a textDocument/rangeFormatting request
        tracing::debug!("Formatting range in {} at {}:{} to {}:{}",
                       file_path.display(), range.start.line, range.start.character,
                       range.end.line, range.end.character);

        // For now, return the original content
        let open_files = self.open_files.read().await;
        if let Some(content) = open_files.get(file_path) {
            Ok(content.clone())
        } else {
            Err(LspError::FileNotOpen(file_path.to_path_buf()))
        }
    }

    /// Simulate receiving diagnostics (for testing/development)
    /// In a real implementation, this would be called when receiving
    /// textDocument/publishDiagnostics notifications
    pub async fn _simulate_diagnostics(&self, file_path: &Path, diagnostics: Vec<LspDiagnostic>) {
        let mut diag_map = self.diagnostics.write().await;
        diag_map.insert(file_path.to_path_buf(), diagnostics);
    }
}

#[async_trait]
impl LspService for LspClient {
    async fn get_diagnostics(&self, file_path: &Path) -> Result<Vec<LspDiagnostic>, LspError> {
        self.get_diagnostics(file_path).await
    }

    async fn did_change_file(&self, file_path: &Path, content: &str) -> Result<(), LspError> {
        self.did_change(file_path, content).await
    }

    async fn did_open_file(&self, file_path: &Path, content: &str) -> Result<(), LspError> {
        self.did_open(file_path, content).await
    }

    async fn did_close_file(&self, file_path: &Path) -> Result<(), LspError> {
        self.did_close(file_path).await
    }

    fn supports_file(&self, file_path: &Path) -> bool {
        self.handles_file(file_path)
    }

    async fn get_completions(&self, file_path: &Path, position: Position) -> Result<Vec<CompletionItem>, LspError> {
        self.get_completions(file_path, position).await
    }

    async fn goto_definition(&self, file_path: &Path, position: Position) -> Result<Vec<Location>, LspError> {
        self.goto_definition(file_path, position).await
    }

    async fn get_hover(&self, file_path: &Path, position: Position) -> Result<Option<Hover>, LspError> {
        self.get_hover(file_path, position).await
    }

    async fn find_references(&self, file_path: &Path, position: Position, include_declaration: bool) -> Result<Vec<Location>, LspError> {
        self.find_references(file_path, position, include_declaration).await
    }

    async fn get_code_actions(&self, file_path: &Path, range: Range) -> Result<Vec<CodeAction>, LspError> {
        self.get_code_actions(file_path, range).await
    }

    async fn get_document_symbols(&self, file_path: &Path) -> Result<Vec<SymbolInformation>, LspError> {
        self.get_document_symbols(file_path).await
    }

    async fn format_document(&self, file_path: &Path) -> Result<String, LspError> {
        self.format_document(file_path).await
    }

    async fn format_range(&self, file_path: &Path, range: Range) -> Result<String, LspError> {
        self.format_range(file_path, range).await
    }
}

impl Drop for LspClient {
    fn drop(&mut self) {
        if let Some(mut process) = self.process.take() {
            // Try to kill the process gracefully
            tokio::spawn(async move {
                if let Err(e) = process.kill().await {
                    tracing::warn!("Failed to kill LSP process in drop: {}", e);
                }
            });
        }
    }
}

/// Convert a file path to an LSP URI
fn path_to_uri(path: &Path) -> Result<Url, LspError> {
    Url::from_file_path(path)
        .map_err(|_| LspError::InvalidResponse(format!("Invalid file path: {}", path.display())))
}

/// Convert an LSP URI to a file path
fn uri_to_path(uri: &Url) -> Result<PathBuf, LspError> {
    uri.to_file_path()
        .map_err(|_| LspError::InvalidResponse(format!("Invalid URI: {}", uri)))
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;
    
    #[tokio::test]
    async fn test_client_creation() {
        let config = LspServerConfig::default();
        let client = LspClient::new(config);
        
        assert!(!client.is_initialized().await);
        assert!(client.get_diagnostics(&PathBuf::from("test.rs")).await.unwrap().is_empty());
    }
    
    #[tokio::test]
    async fn test_file_operations() {
        let config = LspServerConfig::default();
        let mut client = LspClient::new(config);
        
        // Simulate initialization
        {
            let mut initialized = client.initialized.write().await;
            *initialized = true;
        }
        
        let file_path = PathBuf::from("test.rs");
        let content = "fn main() {}";
        
        // Test file operations
        assert!(client.did_open(&file_path, content).await.is_ok());
        assert!(client.did_change(&file_path, "fn main() { println!(\"Hello\"); }").await.is_ok());
        assert!(client.did_close(&file_path).await.is_ok());
    }
    
    #[test]
    fn test_path_uri_conversion() {
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();
        let path = temp_dir.path().join("test.rs");

        let uri = path_to_uri(&path).unwrap();
        let converted_path = uri_to_path(&uri).unwrap();

        assert_eq!(path, converted_path);
    }
}