Skip to main content

rust_meth_lib/
lsp.rs

1// Minimal LSP transport: write Content-Length-framed JSON over stdin,
2// read framed responses from stdout.  No async, no external LSP crate
3// just `BufReader` + `serde_json`.
4
5use std::io::{BufRead, BufReader, Read, Write};
6use std::process::{Child, ChildStdin, ChildStdout};
7
8use crate::error::{Result, RustMethError};
9
10use serde_json::{Value, json};
11
12/// A synchronous transport layer for communicating with a Language Server Protocol (LSP) server.
13pub struct LspTransport {
14    /// The standard input stream used to send messages to the LSP server child process.
15    stdin: ChildStdin,
16    reader: BufReader<ChildStdout>,
17}
18
19impl LspTransport {
20    /// Creates a new `LspTransport` by taking ownership of the `stdin` and `stdout`
21    /// streams from the provided child process.
22    ///
23    /// # Panics
24    ///
25    /// Panics if the child process does not have a captured `stdin` or `stdout` stream
26    /// (e.g., if they weren't configured with `Stdio::piped()`).
27    pub fn new(child: &mut Child) -> Self {
28        let stdin = child.stdin.take().expect("stdin");
29        let stdout = child.stdout.take().expect("stdout");
30        Self {
31            stdin,
32            reader: BufReader::new(stdout),
33        }
34    }
35
36    /// Send a JSON-RPC message.
37    ///
38    /// # Errors
39    ///
40    /// Returns an [`std::io::Error`] if writing to or flushing the underlying `stdin` stream fails.
41    pub fn send(&mut self, msg: &Value) -> std::io::Result<()> {
42        let body = msg.to_string();
43        write!(self.stdin, "Content-Length: {}\r\n\r\n{}", body.len(), body)?;
44        self.stdin.flush()
45    }
46
47    /// Read the next LSP message (blocks until one arrives).
48    ///
49    /// # Errors
50    ///
51    /// Returns an error if:
52    /// - An I/O error occurs while reading from the stdout stream.
53    /// - The stream ends before a valid `Content-Length` header is parsed.
54    /// - The header value cannot be parsed into a valid size.
55    /// - The message body cannot be parsed as valid JSON.
56    pub fn recv(&mut self) -> Result<Value> {
57        // Read headers until blank line.
58        let mut content_length: Option<usize> = None;
59        loop {
60            let mut line = String::new();
61            self.reader.read_line(&mut line)?;
62            let line = line.trim_end_matches(['\r', '\n']);
63            if line.is_empty() {
64                break;
65            }
66            if let Some(val) = line.strip_prefix("Content-Length: ") {
67                content_length = Some(val.trim().parse()?);
68            }
69        }
70
71        let length = content_length.ok_or(RustMethError::NoContentLength)?;
72        let mut body = vec![0u8; length];
73        self.reader.read_exact(&mut body)?;
74        Ok(serde_json::from_slice(&body)?)
75    }
76
77    /// Read messages until `predicate` returns `Some(T)`, discarding everything else.
78    ///
79    /// # Errors
80    ///
81    /// Returns an error if:
82    /// - The underlying [`Self::recv`] call fails.
83    /// - The `limit` number of messages is exhausted without the `predicate` returning `Some(T)`.
84    pub fn recv_until<T>(
85        &mut self,
86        limit: usize,
87        mut predicate: impl FnMut(&Value) -> Option<T>,
88    ) -> Result<T> {
89        for _ in 0..limit {
90            let msg = self.recv()?;
91            if let Some(result) = predicate(&msg) {
92                return Ok(result);
93            }
94        }
95        Err(RustMethError::RecvExhausted { limit })
96    }
97
98    // ── Convenience constructors for common messages ─────────────────────────
99
100    /// Constructs an LSP `initialize` request message.
101    #[must_use]
102    pub fn initialize(process_id: u32, root_uri: &str) -> Value {
103        json!({
104            "jsonrpc": "2.0",
105            "id": 1,
106            "method": "initialize",
107            "params": {
108                "processId": process_id,
109                "rootUri": root_uri,
110                "capabilities": {
111                    "textDocument": {
112                        "completion": {
113                            "completionItem": { "snippetSupport": false }
114                        }
115                    }
116                },
117                "initializationOptions": {
118                    // Ask RA not to load proc-macros — speeds up cold indexing.
119                    "procMacro": { "enable": false }
120                }
121            }
122        })
123    }
124
125    /// Constructs an LSP `initialized` notification message.
126    #[must_use]
127    pub fn initialized() -> Value {
128        json!({ "jsonrpc": "2.0", "method": "initialized", "params": {} })
129    }
130
131    /// Constructs an LSP `textDocument/didOpen` notification message.
132    #[must_use]
133    pub fn did_open(uri: &str, text: &str) -> Value {
134        json!({
135            "jsonrpc": "2.0",
136            "method": "textDocument/didOpen",
137            "params": {
138                "textDocument": {
139                    "uri": uri,
140                    "languageId": "rust",
141                    "version": 1,
142                    "text": text
143                }
144            }
145        })
146    }
147
148    /// Constructs an LSP `textDocument/definition` request message.
149    #[must_use]
150    pub fn definition(id: u64, uri: &str, line: u32, character: u32) -> Value {
151        json!({
152            "jsonrpc": "2.0",
153            "id": id,
154            "method": "textDocument/definition",
155            "params": {
156                "textDocument": { "uri": uri },
157                "position": { "line": line, "character": character }
158            }
159        })
160    }
161
162    /// Constructs an LSP `textDocument/completion` request message.
163    #[must_use]
164    pub fn completion(id: u64, uri: &str, line: u32, character: u32) -> Value {
165        json!({
166            "jsonrpc": "2.0",
167            "id": id,
168            "method": "textDocument/completion",
169            "params": {
170                "textDocument": { "uri": uri },
171                "position": { "line": line, "character": character },
172                "context": { "triggerKind": 2, "triggerCharacter": "." }
173            }
174        })
175    }
176
177    /// Constructs an LSP `shutdown` request message.
178    #[must_use]
179    pub fn shutdown(id: u64) -> Value {
180        json!({ "jsonrpc": "2.0", "id": id, "method": "shutdown", "params": null })
181    }
182
183    /// Constructs an LSP `exit` notification message.
184    #[must_use]
185    pub fn exit() -> Value {
186        json!({ "jsonrpc": "2.0", "method": "exit", "params": null })
187    }
188}
189
190#[cfg(test)]
191mod tests {
192    use super::*;
193
194    // ═══════════════════════════════════════════════════════════════
195    // UNIT TESTS: LSP Message Construction
196    // ═══════════════════════════════════════════════════════════════
197
198    #[test]
199    fn test_initialize_message_structure() {
200        let msg = LspTransport::initialize(12345, "file:///test");
201
202        assert_eq!(msg["jsonrpc"], "2.0");
203        assert_eq!(msg["id"], 1);
204        assert_eq!(msg["method"], "initialize");
205        assert_eq!(msg["params"]["processId"], 12345);
206        assert_eq!(msg["params"]["rootUri"], "file:///test");
207    }
208
209    #[test]
210    fn test_completion_message_structure() {
211        let msg = LspTransport::completion(42, "file:///test.rs", 10, 5);
212
213        assert_eq!(msg["jsonrpc"], "2.0");
214        assert_eq!(msg["id"], 42);
215        assert_eq!(msg["method"], "textDocument/completion");
216        assert_eq!(msg["params"]["position"]["line"], 10);
217        assert_eq!(msg["params"]["position"]["character"], 5);
218        assert_eq!(msg["params"]["context"]["triggerKind"], 2);
219        assert_eq!(msg["params"]["context"]["triggerCharacter"], ".");
220    }
221
222    #[test]
223    fn test_definition_message_structure() {
224        let msg = LspTransport::definition(99, "file:///main.rs", 20, 15);
225
226        assert_eq!(msg["jsonrpc"], "2.0");
227        assert_eq!(msg["id"], 99);
228        assert_eq!(msg["method"], "textDocument/definition");
229        assert_eq!(msg["params"]["textDocument"]["uri"], "file:///main.rs");
230        assert_eq!(msg["params"]["position"]["line"], 20);
231        assert_eq!(msg["params"]["position"]["character"], 15);
232    }
233
234    #[test]
235    fn test_shutdown_and_exit() {
236        let shutdown = LspTransport::shutdown(100);
237        assert_eq!(shutdown["method"], "shutdown");
238        assert_eq!(shutdown["id"], 100);
239
240        let exit = LspTransport::exit();
241        assert_eq!(exit["method"], "exit");
242        assert!(exit["id"].is_null());
243    }
244}