Skip to main content

vibe_lsp/
server.rs

1//! LSP server implementation — JSON-RPC over stdin/stdout (P1.3).
2
3use crate::catalog_intel::{completions_at, hover_at, workspace_edit_for_fix};
4use serde_json::{json, Value};
5use std::collections::HashMap;
6use std::io::{self, BufRead, Write};
7use vibe::projectional::{project_program, ProjectOptions};
8use vibe::{check_program, parse_program, Diagnostic};
9
10/// LSP message framing: Content-Length header + blank line + JSON body.
11pub fn encode_message(json: &str) -> String {
12    format!("Content-Length: {}\r\n\r\n{}", json.len(), json)
13}
14
15/// Read one LSP message from the reader. Returns None on EOF.
16pub fn read_message<R: BufRead>(reader: &mut R) -> io::Result<Option<String>> {
17    let mut content_length: Option<usize> = None;
18    let mut line = String::new();
19
20    // Read headers until blank line.
21    loop {
22        line.clear();
23        let n = reader.read_line(&mut line)?;
24        if n == 0 {
25            return Ok(None); // EOF
26        }
27        let trimmed = line.trim_end();
28        if trimmed.is_empty() {
29            break; // End of headers
30        }
31        if let Some(rest) = trimmed.strip_prefix("Content-Length: ") {
32            content_length = rest.parse::<usize>().ok();
33        }
34    }
35
36    let len = match content_length {
37        Some(l) => l,
38        None => return Ok(None),
39    };
40
41    let mut body = vec![0u8; len];
42    reader.read_exact(&mut body)?;
43    Ok(Some(String::from_utf8_lossy(&body).to_string()))
44}
45
46/// Convert a byte offset to an LSP (0-based line, 0-based character) position.
47pub fn offset_to_position(src: &str, offset: usize) -> (usize, usize) {
48    let mut line = 0;
49    let mut character = 0;
50    let mut current_offset = 0;
51
52    for ch in src.chars() {
53        if current_offset >= offset {
54            break;
55        }
56        if ch == '\n' {
57            line += 1;
58            character = 0;
59        } else {
60            character += ch.len_utf16();
61        }
62        current_offset += ch.len_utf8();
63    }
64    (line, character)
65}
66
67/// Convert a vibe Diagnostic to an LSP diagnostic JSON value (with source text for exact line/col).
68pub fn diagnostic_to_lsp_with_src(diag: &Diagnostic, src: &str) -> Value {
69    let (start_line, start_char) = offset_to_position(src, diag.span.start as usize);
70    let (end_line, mut end_char) = offset_to_position(src, diag.span.end as usize);
71    if start_line == end_line && start_char == end_char {
72        end_char = start_char + 1;
73    }
74
75    let mut map = serde_json::Map::new();
76    map.insert(
77        "range".to_string(),
78        json!({
79            "start": { "line": start_line, "character": start_char },
80            "end": { "line": end_line, "character": end_char }
81        }),
82    );
83    map.insert("severity".to_string(), json!(severity_for_code(&diag.code)));
84    map.insert("code".to_string(), json!(format!("{:?}", diag.code)));
85    map.insert("message".to_string(), json!(diag.message));
86    if let Some(fix) = &diag.suggested_fix {
87        map.insert("data".to_string(), json!({ "suggested_fix": fix }));
88    }
89
90    Value::Object(map)
91}
92
93#[allow(dead_code)]
94/// Diagnostic to LSP form.
95pub fn diagnostic_to_lsp(diag: &Diagnostic) -> Value {
96    let (line, character) = (0, diag.span.start as usize);
97    json!({
98        "range": {
99            "start": { "line": line, "character": character },
100            "end": { "line": line, "character": character + 1 }
101        },
102        "severity": severity_for_code(&diag.code),
103        "code": format!("{:?}", diag.code),
104        "message": diag.message,
105    })
106}
107
108/// Map a DiagCode to an LSP severity (1=Error, 2=Warning, 3=Info, 4=Hint).
109fn severity_for_code(code: &vibe::DiagCode) -> u8 {
110    match code {
111        vibe::DiagCode::E001 => 1, // parse error
112        vibe::DiagCode::E100 => 1, // unknown binding
113        vibe::DiagCode::E200 => 1, // effect mismatch
114        vibe::DiagCode::E300 => 1, // missing capability
115        vibe::DiagCode::E600 => 1, // runtime error
116        vibe::DiagCode::E701 => 1, // mut violation
117        vibe::DiagCode::E702 => 2, // capability unavailable — warning
118        _ => 1,
119    }
120}
121
122/// Get diagnostics for a VibeScript source string.
123pub fn get_diagnostics(src: &str) -> Vec<Value> {
124    match parse_program(src) {
125        Ok(program) => match check_program(&program) {
126            Ok(_) => Vec::new(),
127            Err(diag) => vec![diagnostic_to_lsp_with_src(&diag, src)],
128        },
129        Err(diag) => vec![diagnostic_to_lsp_with_src(&diag, src)],
130    }
131}
132
133/// The LSP server state.
134pub struct LspServer<R: BufRead, W: Write> {
135    reader: R,
136    writer: W,
137    documents: HashMap<String, String>,
138    shutdown: bool,
139}
140
141impl<R: BufRead, W: Write> LspServer<R, W> {
142    /// Creates a new instance.
143    pub fn new(reader: R, writer: W) -> Self {
144        Self {
145            reader,
146            writer,
147            documents: HashMap::new(),
148            shutdown: false,
149        }
150    }
151
152    /// Run the server loop.
153    pub fn run(&mut self) -> io::Result<()> {
154        loop {
155            let msg = match read_message(&mut self.reader)? {
156                Some(m) => m,
157                None => return Ok(()), // EOF
158            };
159            let request: Value = match serde_json::from_str(&msg) {
160                Ok(v) => v,
161                Err(_) => continue,
162            };
163            self.handle_message(request)?;
164            if self.shutdown {
165                return Ok(());
166            }
167        }
168    }
169
170    fn send_response(&mut self, response: Value) -> io::Result<()> {
171        let json = serde_json::to_string(&response)?;
172        let framed = encode_message(&json);
173        self.writer.write_all(framed.as_bytes())?;
174        self.writer.flush()
175    }
176
177    fn send_notification(&mut self, method: &str, params: Value) -> io::Result<()> {
178        let notification = json!({
179            "jsonrpc": "2.0",
180            "method": method,
181            "params": params,
182        });
183        self.send_response(notification)
184    }
185
186    fn handle_message(&mut self, msg: Value) -> io::Result<()> {
187        let method = msg.get("method").and_then(|m| m.as_str()).unwrap_or("");
188        let id = msg.get("id").cloned();
189
190        match method {
191            "initialize" => {
192                let response = json!({
193                    "jsonrpc": "2.0",
194                    "id": id,
195                    "result": {
196                        "capabilities": {
197                            "textDocumentSync": 1, // full sync
198                            "diagnosticProvider": true,
199                            "completionProvider": {
200                                "triggerCharacters": [".", ":", "\"", "(", "{"]
201                            },
202                            "hoverProvider": true,
203                            "codeActionProvider": true,
204                            "documentFormattingProvider": true,
205                        },
206                        "serverInfo": {
207                            "name": "vibe-lsp",
208                            "version": "0.0.32",
209                        }
210                    }
211                });
212                self.send_response(response)?;
213            }
214            "initialized" => {
215                // No response needed for notification.
216            }
217            "shutdown" => {
218                self.shutdown = true;
219                let response = json!({ "jsonrpc": "2.0", "id": id, "result": null });
220                self.send_response(response)?;
221            }
222            "exit" => {
223                return Ok(());
224            }
225            "textDocument/didOpen" => {
226                if let Some(params) = msg.get("params") {
227                    if let Some(uri) = params.pointer("/textDocument/uri").and_then(|v| v.as_str())
228                    {
229                        let text = params
230                            .pointer("/textDocument/text")
231                            .and_then(|v| v.as_str())
232                            .unwrap_or("");
233                        self.documents.insert(uri.to_string(), text.to_string());
234                        self.publish_diagnostics(uri)?;
235                    }
236                }
237            }
238            "textDocument/didChange" => {
239                if let Some(params) = msg.get("params") {
240                    if let Some(uri) = params.pointer("/textDocument/uri").and_then(|v| v.as_str())
241                    {
242                        // Full sync: take the last change.
243                        if let Some(changes) =
244                            params.pointer("/contentChanges").and_then(|v| v.as_array())
245                        {
246                            if let Some(last) = changes.last() {
247                                if let Some(text) = last.get("text").and_then(|v| v.as_str()) {
248                                    self.documents.insert(uri.to_string(), text.to_string());
249                                }
250                            }
251                        }
252                        self.publish_diagnostics(uri)?;
253                    }
254                }
255            }
256            "textDocument/completion" => {
257                let (src, line, character) = self.completion_context(msg.get("params"));
258                let completions = completions_at(&src, line, character);
259                let response = json!({
260                    "jsonrpc": "2.0",
261                    "id": id,
262                    "result": completions,
263                });
264                self.send_response(response)?;
265            }
266            "textDocument/hover" => {
267                let (src, line, character) = self.completion_context(msg.get("params"));
268                let hover_text = hover_at(&src, line, character);
269                let response = json!({
270                    "jsonrpc": "2.0",
271                    "id": id,
272                    "result": {
273                        "contents": {
274                            "kind": "markdown",
275                            "value": hover_text,
276                        }
277                    }
278                });
279                self.send_response(response)?;
280            }
281            "textDocument/codeAction" => {
282                let mut actions = Vec::new();
283                if let Some(params) = msg.get("params") {
284                    let uri = params
285                        .pointer("/textDocument/uri")
286                        .and_then(|v| v.as_str())
287                        .unwrap_or("");
288                    let src = self.documents.get(uri).cloned().unwrap_or_default();
289                    if let Some(diags) = params
290                        .pointer("/context/diagnostics")
291                        .and_then(|v| v.as_array())
292                    {
293                        for d in diags {
294                            if let Some(fix) =
295                                d.pointer("/data/suggested_fix").and_then(|v| v.as_str())
296                            {
297                                let mut action = json!({
298                                    "title": format!("Apply fix: {fix}"),
299                                    "kind": "quickfix",
300                                    "diagnostics": [d],
301                                    "isPreferred": true,
302                                });
303                                if let Some(edit) = workspace_edit_for_fix(uri, d, &src) {
304                                    action["edit"] = edit;
305                                }
306                                actions.push(action);
307                            }
308                        }
309                    }
310                }
311                let response = json!({
312                    "jsonrpc": "2.0",
313                    "id": id,
314                    "result": actions,
315                });
316                self.send_response(response)?;
317            }
318            "textDocument/formatting" => {
319                let mut edits = Vec::new();
320                if let Some(params) = msg.get("params") {
321                    if let Some(uri) = params.pointer("/textDocument/uri").and_then(|v| v.as_str())
322                    {
323                        if let Some(text) = self.documents.get(uri) {
324                            if let Ok(prog) = parse_program(text) {
325                                let formatted = project_program(
326                                    &prog,
327                                    &ProjectOptions {
328                                        indent: "  ".to_string(),
329                                        blank_lines_between_decls: 1,
330                                        max_line_width: 80,
331                                    },
332                                );
333                                let (end_line, end_char) = offset_to_position(text, text.len());
334                                edits.push(json!({
335                                    "range": {
336                                        "start": { "line": 0, "character": 0 },
337                                        "end": { "line": end_line, "character": end_char }
338                                    },
339                                    "newText": formatted,
340                                }));
341                            }
342                        }
343                    }
344                }
345                let response = json!({
346                    "jsonrpc": "2.0",
347                    "id": id,
348                    "result": edits,
349                });
350                self.send_response(response)?;
351            }
352            _ => {
353                // Unknown method — send method not found if it has an id.
354                if let Some(id) = id {
355                    let response = json!({
356                        "jsonrpc": "2.0",
357                        "id": id,
358                        "error": { "code": -32601, "message": "method not found" }
359                    });
360                    self.send_response(response)?;
361                }
362            }
363        }
364        Ok(())
365    }
366
367    fn completion_context(&self, params: Option<&Value>) -> (String, usize, usize) {
368        let Some(params) = params else {
369            return (String::new(), 0, 0);
370        };
371        let uri = params
372            .pointer("/textDocument/uri")
373            .and_then(|v| v.as_str())
374            .unwrap_or("");
375        let src = self.documents.get(uri).cloned().unwrap_or_default();
376        let line = params
377            .pointer("/position/line")
378            .and_then(|v| v.as_u64())
379            .unwrap_or(0) as usize;
380        let character = params
381            .pointer("/position/character")
382            .and_then(|v| v.as_u64())
383            .unwrap_or(0) as usize;
384        (src, line, character)
385    }
386
387    fn publish_diagnostics(&mut self, uri: &str) -> io::Result<()> {
388        let text = self.documents.get(uri).cloned().unwrap_or_default();
389        let diags = get_diagnostics(&text);
390        self.send_notification(
391            "textDocument/publishDiagnostics",
392            json!({
393                "uri": uri,
394                "diagnostics": diags,
395            }),
396        )
397    }
398}
399
400#[cfg(test)]
401mod tests {
402    use super::*;
403    use std::io::{BufReader, Cursor};
404
405    #[test]
406    fn lsp_message_framing() {
407        let body = r#"{"jsonrpc":"2.0","method":"test"}"#;
408        let framed = encode_message(body);
409        assert!(framed.starts_with("Content-Length: "));
410        assert!(framed.contains("\r\n\r\n"));
411        assert!(framed.ends_with(body));
412
413        // Round-trip: read it back.
414        let mut reader = BufReader::new(Cursor::new(framed.as_bytes()));
415        let msg = read_message(&mut reader).unwrap().unwrap();
416        assert_eq!(msg, body);
417    }
418
419    #[test]
420    fn initialize_response() {
421        let input = encode_message(r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}"#);
422        let mut output = Vec::new();
423        {
424            let reader = BufReader::new(Cursor::new(input.as_bytes()));
425            let writer = Cursor::new(&mut output);
426            let mut server = LspServer::new(reader, writer);
427            server.run().unwrap();
428        }
429        let output_str = String::from_utf8(output).unwrap();
430        assert!(output_str.contains("vibe-lsp"));
431        assert!(output_str.contains("capabilities"));
432        assert!(output_str.contains("textDocumentSync"));
433        assert!(output_str.contains("completionProvider"));
434    }
435
436    #[test]
437    fn diagnostics_on_parse_error() {
438        let bad_src = "fn main() { let x = ; }";
439        let diags = get_diagnostics(bad_src);
440        assert!(!diags.is_empty());
441        assert!(diags[0].get("message").is_some());
442        assert!(diags[0].get("range").is_some());
443    }
444
445    #[test]
446    fn diagnostics_on_valid_program() {
447        let good_src = "fn main() { return 42; }";
448        let diags = get_diagnostics(good_src);
449        assert!(diags.is_empty(), "expected no diagnostics, got {:?}", diags);
450    }
451
452    #[test]
453    fn did_open_publishes_diagnostics() {
454        let bad_src = "fn main() { let x = ; }";
455        let body = serde_json::to_string(&json!({
456            "jsonrpc": "2.0",
457            "method": "textDocument/didOpen",
458            "params": {
459                "textDocument": {
460                    "uri": "file:///test.vibe",
461                    "languageId": "vibe",
462                    "version": 1,
463                    "text": bad_src,
464                }
465            }
466        }))
467        .unwrap();
468        let input = encode_message(&body);
469        let mut output = Vec::new();
470        {
471            let reader = BufReader::new(Cursor::new(input.as_bytes()));
472            let writer = Cursor::new(&mut output);
473            let mut server = LspServer::new(reader, writer);
474            server.run().unwrap();
475        }
476        let output_str = String::from_utf8(output).unwrap();
477        assert!(output_str.contains("publishDiagnostics"));
478        assert!(output_str.contains("file:///test.vibe"));
479    }
480
481    #[test]
482    fn completion_response() {
483        let input = encode_message(
484            r#"{"jsonrpc":"2.0","id":2,"method":"textDocument/completion","params":{"textDocument":{"uri":"file:///test.vibe"},"position":{"line":0,"character":0}}}"#,
485        );
486        let mut output = Vec::new();
487        {
488            let reader = BufReader::new(Cursor::new(input.as_bytes()));
489            let writer = Cursor::new(&mut output);
490            let mut server = LspServer::new(reader, writer);
491            server.run().unwrap();
492        }
493        let output_str = String::from_utf8(output).unwrap();
494        assert!(output_str.contains("cell"));
495        assert!(output_str.contains("Animation"));
496        assert!(output_str.contains("using"));
497    }
498
499    #[test]
500    fn formatting_response() {
501        let unformatted = "fn main(){return 42;}";
502        let body = serde_json::to_string(&json!({
503            "jsonrpc": "2.0",
504            "method": "textDocument/didOpen",
505            "params": {
506                "textDocument": {
507                    "uri": "file:///test.vibe",
508                    "languageId": "vibe",
509                    "version": 1,
510                    "text": unformatted,
511                }
512            }
513        }))
514        .unwrap();
515        let format_req = encode_message(
516            r#"{"jsonrpc":"2.0","id":3,"method":"textDocument/formatting","params":{"textDocument":{"uri":"file:///test.vibe"},"options":{"tabSize":2,"insertSpaces":true}}}"#,
517        );
518        let input = format!("{}{}", encode_message(&body), format_req);
519        let mut output = Vec::new();
520        {
521            let reader = BufReader::new(Cursor::new(input.as_bytes()));
522            let writer = Cursor::new(&mut output);
523            let mut server = LspServer::new(reader, writer);
524            server.run().unwrap();
525        }
526        let output_str = String::from_utf8(output).unwrap();
527        assert!(output_str.contains("newText"));
528    }
529
530    #[test]
531    fn shutdown_then_exit() {
532        let shutdown = encode_message(r#"{"jsonrpc":"2.0","id":1,"method":"shutdown"}"#);
533        let exit = encode_message(r#"{"jsonrpc":"2.0","method":"exit"}"#);
534        let input = format!("{shutdown}{exit}");
535        let mut output = Vec::new();
536        {
537            let reader = BufReader::new(Cursor::new(input.as_bytes()));
538            let writer = Cursor::new(&mut output);
539            let mut server = LspServer::new(reader, writer);
540            server.run().unwrap();
541        }
542        let output_str = String::from_utf8(output).unwrap();
543        assert!(output_str.contains("null"));
544    }
545
546    #[test]
547    fn read_message_eof() {
548        let mut reader = BufReader::new(Cursor::new(b""));
549        let result = read_message(&mut reader).unwrap();
550        assert!(result.is_none());
551    }
552}