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) -> 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 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 pub fn recv(&mut self) -> Result<Value> {
57 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 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 #[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 "procMacro": { "enable": false }
120 }
121 }
122 })
123 }
124
125 #[must_use]
127 pub fn initialized() -> Value {
128 json!({ "jsonrpc": "2.0", "method": "initialized", "params": {} })
129 }
130
131 #[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 #[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 #[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 #[must_use]
179 pub fn shutdown(id: u64) -> Value {
180 json!({ "jsonrpc": "2.0", "id": id, "method": "shutdown", "params": null })
181 }
182
183 #[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 #[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}