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