1use 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
12pub struct LspTransport {
14 stdin: ChildStdin,
16 reader: BufReader<ChildStdout>,
17}
18
19impl LspTransport {
20 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 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 pub fn recv(&mut self) -> Result<Value> {
58 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 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 #[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 "procMacro": { "enable": false }
121 }
122 }
123 })
124 }
125
126 #[must_use]
128 pub fn initialized() -> Value {
129 json!({ "jsonrpc": "2.0", "method": "initialized", "params": {} })
130 }
131
132 #[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 #[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 #[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 #[must_use]
180 pub fn shutdown(id: u64) -> Value {
181 json!({ "jsonrpc": "2.0", "id": id, "method": "shutdown", "params": null })
182 }
183
184 #[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 #[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}