1pub mod analysis;
16
17use std::collections::HashMap;
18use std::io::{BufRead, Write};
19
20use serde_json::{json, Value};
21
22pub use analysis::{
23 analyze, build_index, code_actions, completion_items, definition_at, diagnostics,
24 format_source, hover_markdown, inlay_hints, references_at, word_at_pos, Diagnostic, InlayHint,
25 Location, QuickFix, SymKind, Symbol, SymbolIndex,
26};
27
28pub struct Server {
30 documents: HashMap<String, String>,
31 shutdown: bool,
32 exit: bool,
33}
34
35impl Default for Server {
36 fn default() -> Self {
37 Self::new()
38 }
39}
40
41impl Server {
42 pub fn new() -> Self {
53 Server {
54 documents: HashMap::new(),
55 shutdown: false,
56 exit: false,
57 }
58 }
59
60 pub fn should_exit(&self) -> bool {
78 self.exit
79 }
80
81 pub fn handle(&mut self, msg: &Value) -> Vec<Value> {
116 let method = msg.get("method").and_then(Value::as_str).unwrap_or("");
117 let id = msg.get("id").cloned();
118
119 match method {
120 "initialize" => vec![response(
121 id,
122 json!({
123 "capabilities": {
124 "textDocumentSync": 1,
125 "hoverProvider": true,
126 "codeActionProvider": true,
127 "documentFormattingProvider": true,
128 "definitionProvider": true,
129 "referencesProvider": true,
130 "completionProvider": { "triggerCharacters": [".", "("] },
131 "inlayHintProvider": true
132 },
133 "serverInfo": { "name": "telos-lsp", "version": env!("CARGO_PKG_VERSION") }
134 }),
135 )],
136 "initialized" => vec![],
137 "shutdown" => {
138 self.shutdown = true;
139 vec![response(id, Value::Null)]
140 }
141 "exit" => {
142 self.exit = true;
143 vec![]
144 }
145 "textDocument/didOpen" => {
146 let uri = msg["params"]["textDocument"]["uri"]
147 .as_str()
148 .unwrap_or("")
149 .to_string();
150 let text = msg["params"]["textDocument"]["text"]
151 .as_str()
152 .unwrap_or("")
153 .to_string();
154 self.documents.insert(uri.clone(), text);
155 vec![self.publish(&uri)]
156 }
157 "textDocument/didChange" => {
158 let uri = msg["params"]["textDocument"]["uri"]
159 .as_str()
160 .unwrap_or("")
161 .to_string();
162 if let Some(changes) = msg["params"]["contentChanges"].as_array() {
163 if let Some(last) = changes.last() {
164 if let Some(text) = last["text"].as_str() {
165 self.documents.insert(uri.clone(), text.to_string());
166 }
167 }
168 }
169 vec![self.publish(&uri)]
170 }
171 "textDocument/didSave" => {
172 let uri = msg["params"]["textDocument"]["uri"]
173 .as_str()
174 .unwrap_or("")
175 .to_string();
176 vec![self.publish(&uri)]
177 }
178 "textDocument/didClose" => {
179 let uri = msg["params"]["textDocument"]["uri"]
180 .as_str()
181 .unwrap_or("")
182 .to_string();
183 self.documents.remove(&uri);
184 vec![publish_diagnostics(&uri, &[])]
185 }
186 "textDocument/hover" => {
187 let uri = msg["params"]["textDocument"]["uri"].as_str().unwrap_or("");
188 let line = msg["params"]["position"]["line"].as_u64().unwrap_or(0) as usize;
189 let ch = msg["params"]["position"]["character"].as_u64().unwrap_or(0) as usize;
190 let result = self
191 .documents
192 .get(uri)
193 .and_then(|text| hover_markdown(text, line, ch))
194 .map(|md| json!({ "contents": { "kind": "markdown", "value": md } }))
195 .unwrap_or(Value::Null);
196 vec![response(id, result)]
197 }
198 "textDocument/codeAction" => {
199 let uri = msg["params"]["textDocument"]["uri"]
200 .as_str()
201 .unwrap_or("")
202 .to_string();
203 let actions: Vec<Value> = self
204 .documents
205 .get(&uri)
206 .map(|text| code_actions(text))
207 .unwrap_or_default()
208 .into_iter()
209 .map(|fix| {
210 json!({
211 "title": fix.title,
212 "kind": "quickfix",
213 "edit": {
214 "changes": {
215 uri.clone(): [{
216 "range": {
217 "start": { "line": fix.line, "character": 0 },
218 "end": { "line": fix.line, "character": 0 }
219 },
220 "newText": fix.new_text
221 }]
222 }
223 }
224 })
225 })
226 .collect();
227 vec![response(id, json!(actions))]
228 }
229 "textDocument/formatting" => {
230 let uri = msg["params"]["textDocument"]["uri"]
231 .as_str()
232 .unwrap_or("")
233 .to_string();
234 let result = match self.documents.get(&uri) {
235 Some(text) => match format_source(text) {
236 Ok(formatted) => {
237 let line_count = text.lines().count();
238 let last_line_len = text.lines().last().map(|l| l.len()).unwrap_or(0);
239 json!([{
240 "range": {
241 "start": { "line": 0, "character": 0 },
242 "end": {
243 "line": line_count,
244 "character": last_line_len
245 }
246 },
247 "newText": formatted
248 }])
249 }
250 Err(_) => json!([]),
251 },
252 None => json!([]),
253 };
254 vec![response(id, result)]
255 }
256 "telos/verify" => {
257 let uri = msg["params"]["uri"].as_str().unwrap_or("");
258 let result = match self.documents.get(uri) {
259 Some(text) => verify_summary(text),
260 None => json!({ "error": "document not open" }),
261 };
262 vec![response(id, result)]
263 }
264 "telos/eject" => {
265 let uri = msg["params"]["uri"].as_str().unwrap_or("");
266 let func = msg["params"]["func"].as_str();
267 let result = match self.documents.get(uri) {
268 Some(text) => match eject_preview(text, func) {
269 Ok(preview) => json!({ "preview": preview }),
270 Err(e) => json!({ "error": e }),
271 },
272 None => json!({ "error": "document not open" }),
273 };
274 vec![response(id, result)]
275 }
276 "textDocument/definition" => {
277 let uri = msg["params"]["textDocument"]["uri"].as_str().unwrap_or("");
278 let line = msg["params"]["position"]["line"].as_u64().unwrap_or(0) as usize;
279 let ch = msg["params"]["position"]["character"].as_u64().unwrap_or(0) as usize;
280 let docs = self.index_docs();
281 let out = self
282 .documents
283 .get(uri)
284 .and_then(|text| word_at_pos(text, line, ch))
285 .and_then(|w| {
286 let idx = build_index(&docs);
287 definition_at(&idx, &w)
288 })
289 .map(location_to_json)
290 .unwrap_or(Value::Null);
291 vec![response(id, out)]
292 }
293 "textDocument/references" => {
294 let uri = msg["params"]["textDocument"]["uri"].as_str().unwrap_or("");
295 let line = msg["params"]["position"]["line"].as_u64().unwrap_or(0) as usize;
296 let ch = msg["params"]["position"]["character"].as_u64().unwrap_or(0) as usize;
297 let docs = self.index_docs();
298 let locations = self
299 .documents
300 .get(uri)
301 .and_then(|text| word_at_pos(text, line, ch))
302 .map(|w| {
303 let idx = build_index(&docs);
304 references_at(&idx, &w)
305 .into_iter()
306 .map(location_to_json)
307 .collect::<Vec<_>>()
308 })
309 .unwrap_or_default();
310 vec![response(id, json!(locations))]
311 }
312 "textDocument/completion" => {
313 let uri = msg["params"]["textDocument"]["uri"].as_str().unwrap_or("");
314 let items = match self.documents.get(uri) {
315 Some(_) => {
316 let docs = self.index_docs();
317 let idx = build_index(&docs);
318 completion_items(&idx)
319 .into_iter()
320 .map(|(label, kind)| json!({ "label": label, "kind": kind }))
321 .collect::<Vec<_>>()
322 }
323 None => Vec::new(),
324 };
325 vec![response(id, json!(items))]
326 }
327 "textDocument/inlayHint" => {
328 let uri = msg["params"]["textDocument"]["uri"].as_str().unwrap_or("");
329 let hints = self
330 .documents
331 .get(uri)
332 .map(|text| inlay_hints(text, uri))
333 .unwrap_or_default()
334 .into_iter()
335 .map(|h| {
336 json!({
337 "position": { "line": h.line, "character": h.character },
338 "label": h.label,
339 "kind": h.kind,
340 "paddingLeft": true
341 })
342 })
343 .collect::<Vec<_>>();
344 vec![response(id, json!(hints))]
345 }
346 _ => {
347 if id.is_some() {
348 vec![error_response(
349 id,
350 -32601,
351 &format!("method not found: {method}"),
352 )]
353 } else {
354 vec![]
355 }
356 }
357 }
358 }
359
360 fn publish(&self, uri: &str) -> Value {
361 let diags = self
362 .documents
363 .get(uri)
364 .map(|text| diagnostics(text))
365 .unwrap_or_default();
366 publish_diagnostics(uri, &diags)
367 }
368
369 fn index_docs(&self) -> Vec<(String, String)> {
372 self.documents
373 .iter()
374 .map(|(u, t)| (u.clone(), t.clone()))
375 .collect()
376 }
377}
378
379fn verify_summary(text: &str) -> Value {
380 match analyze(text) {
381 Err(e) => json!({ "ok": false, "error": e }),
382 Ok(reports) => {
383 let funcs: Vec<Value> = reports
384 .iter()
385 .map(|r| {
386 json!({
387 "module": r.module,
388 "func": r.name,
389 "target": r.target,
390 "ejected": r.ejected,
391 "verified": r.verified,
392 "failures": r.failures,
393 })
394 })
395 .collect();
396 let all = reports.iter().all(|r| r.verified || r.ejected);
397 json!({ "ok": all, "functions": funcs })
398 }
399 }
400}
401
402fn eject_preview(text: &str, func: Option<&str>) -> Result<String, String> {
403 use tpt_telos_parser::ast::{Arg, Attribute, Item};
404
405 let mut modules = tpt_telos_parser::parse(text)?;
406 let agent = tpt_telos_agent::StaticAgent::new();
407 let mut outcomes = Vec::new();
408 for m in &modules {
409 outcomes.extend(tpt_telos_agent::transpile_module(m, &agent)?);
410 }
411
412 let mut matched = false;
413 for m in &mut modules {
414 let lang = tpt_telos_router::route(&m.attributes)
415 .target
416 .as_str()
417 .to_string();
418 for item in &mut m.items {
419 if let Item::Func(f) = item {
420 let selected = func.map(|n| n == f.name).unwrap_or(true);
421 if selected && !f.is_ejected() {
422 f.attributes.push(Attribute {
423 name: "eject".to_string(),
424 args: vec![Arg::Flag(lang.clone())],
425 });
426 }
427 if selected {
428 matched = true;
429 }
430 }
431 }
432 }
433 if !matched {
434 return Err(format!(
435 "no matching function to eject{}",
436 func.map(|n| format!(" (`{n}`)")).unwrap_or_default()
437 ));
438 }
439
440 let project = tpt_telos_codegen::generate_project(&modules, &outcomes)?;
441 let mut preview = String::new();
442 for f in &project.files {
443 if f.path.ends_with(".rs") || f.path.ends_with(".go") {
444 preview.push_str(&format!("// ===== {} =====\n", f.path));
445 preview.push_str(&f.contents);
446 preview.push('\n');
447 }
448 }
449 Ok(preview)
450}
451
452fn response(id: Option<Value>, result: Value) -> Value {
453 json!({ "jsonrpc": "2.0", "id": id.unwrap_or(Value::Null), "result": result })
454}
455
456fn error_response(id: Option<Value>, code: i64, message: &str) -> Value {
457 json!({ "jsonrpc": "2.0", "id": id.unwrap_or(Value::Null), "error": { "code": code, "message": message } })
458}
459
460fn publish_diagnostics(uri: &str, diags: &[Diagnostic]) -> Value {
461 let items: Vec<Value> = diags
462 .iter()
463 .map(|d| {
464 json!({
465 "range": {
466 "start": { "line": d.line, "character": d.character },
467 "end": { "line": d.end_line, "character": d.end_character }
468 },
469 "severity": d.severity,
470 "source": "telos",
471 "message": d.message,
472 })
473 })
474 .collect();
475 json!({
476 "jsonrpc": "2.0",
477 "method": "textDocument/publishDiagnostics",
478 "params": { "uri": uri, "diagnostics": items }
479 })
480}
481
482fn location_to_json(loc: Location) -> Value {
483 json!({
484 "uri": loc.uri,
485 "range": {
486 "start": { "line": loc.line, "character": loc.character },
487 "end": { "line": loc.end_line, "character": loc.end_character }
488 }
489 })
490}
491
492pub fn run_stdio() -> std::io::Result<()> {
517 let stdin = std::io::stdin();
518 let mut reader = stdin.lock();
519 let stdout = std::io::stdout();
520 let mut writer = stdout.lock();
521 let mut server = Server::new();
522
523 while let Some(msg) = read_message(&mut reader)? {
524 for out in server.handle(&msg) {
525 write_message(&mut writer, &out)?;
526 }
527 if server.should_exit() {
528 break;
529 }
530 }
531 Ok(())
532}
533
534fn read_message<R: BufRead>(reader: &mut R) -> std::io::Result<Option<Value>> {
536 let mut content_length: Option<usize> = None;
537 loop {
538 let mut header = String::new();
539 let n = reader.read_line(&mut header)?;
540 if n == 0 {
541 return Ok(None); }
543 let trimmed = header.trim_end_matches(['\r', '\n']);
544 if trimmed.is_empty() {
545 break; }
547 if let Some(rest) = trimmed
548 .strip_prefix("Content-Length:")
549 .or_else(|| trimmed.strip_prefix("content-length:"))
550 {
551 content_length = rest.trim().parse::<usize>().ok();
552 }
553 }
554
555 let len = match content_length {
556 Some(l) => l,
557 None => return Ok(None),
558 };
559
560 let mut buf = vec![0u8; len];
561 reader.read_exact(&mut buf)?;
562 match serde_json::from_slice::<Value>(&buf) {
563 Ok(v) => Ok(Some(v)),
564 Err(_) => Ok(Some(Value::Null)),
565 }
566}
567
568fn write_message<W: Write>(writer: &mut W, msg: &Value) -> std::io::Result<()> {
570 let body = serde_json::to_string(msg).unwrap_or_else(|_| "null".to_string());
571 write!(writer, "Content-Length: {}\r\n\r\n{}", body.len(), body)?;
572 writer.flush()
573}
574
575#[cfg(test)]
576mod tests {
577 use super::*;
578 use std::io::Cursor;
579
580 #[test]
581 fn framing_round_trips() {
582 let msg = json!({ "jsonrpc": "2.0", "id": 1, "method": "ping" });
583 let mut buf = Vec::new();
584 write_message(&mut buf, &msg).unwrap();
585
586 let framed = String::from_utf8(buf.clone()).unwrap();
587 assert!(framed.starts_with("Content-Length: "));
588 assert!(framed.contains("\r\n\r\n"));
589
590 let mut reader = Cursor::new(buf);
591 let back = read_message(&mut reader).unwrap().unwrap();
592 assert_eq!(back, msg);
593 assert!(read_message(&mut reader).unwrap().is_none());
595 }
596
597 #[test]
598 fn handle_code_action_suggests_requires_fix() {
599 let mut s = Server::new();
600 let src = r#"
601 module Bank {
602 invariant Wallet { balance >= 0 }
603 func withdraw(w: Wallet, amount: Int)
604 ensures w.balance == old(w.balance) - amount
605 { mutate state { w.balance -= amount } }
606 }
607 "#;
608 s.handle(&json!({
609 "jsonrpc": "2.0", "method": "textDocument/didOpen",
610 "params": { "textDocument": { "uri": "u", "text": src } }
611 }));
612 let out = s.handle(&json!({
613 "jsonrpc": "2.0", "id": 2, "method": "textDocument/codeAction",
614 "params": { "textDocument": { "uri": "u" } }
615 }));
616 let actions = out[0]["result"].as_array().unwrap();
617 assert!(!actions.is_empty());
618 assert_eq!(actions[0]["kind"], json!("quickfix"));
619 assert!(actions[0]["edit"]["changes"]["u"][0]["newText"]
620 .as_str()
621 .unwrap()
622 .contains("requires"));
623 }
624
625 #[test]
626 fn handle_did_change_updates_document() {
627 let mut s = Server::new();
628 s.handle(&json!({
629 "jsonrpc": "2.0", "method": "textDocument/didOpen",
630 "params": { "textDocument": { "uri": "u", "text": "module M {}" } }
631 }));
632 let out = s.handle(&json!({
633 "jsonrpc": "2.0", "method": "textDocument/didChange",
634 "params": {
635 "textDocument": { "uri": "u" },
636 "contentChanges": [ { "text": "module M { invariant W { balance >= 0 } }" } ]
637 }
638 }));
639 assert_eq!(out[0]["method"], json!("textDocument/publishDiagnostics"));
640 }
641
642 #[test]
643 fn handle_definition_resolves_to_func() {
644 let mut s = Server::new();
645 let src = "module M {\n func f() ;\n func g() { f() }\n}";
646 s.handle(&json!({
647 "jsonrpc": "2.0", "method": "textDocument/didOpen",
648 "params": { "textDocument": { "uri": "u", "text": src } }
649 }));
650 let out = s.handle(&json!({
652 "jsonrpc": "2.0", "id": 9, "method": "textDocument/definition",
653 "params": { "textDocument": { "uri": "u" }, "position": { "line": 2, "character": 15 } }
654 }));
655 let loc = &out[0]["result"];
656 assert_eq!(loc["uri"], json!("u"));
657 assert_eq!(loc["range"]["start"]["line"], json!(1));
659 }
660
661 #[test]
662 fn handle_references_finds_call_site() {
663 let mut s = Server::new();
664 let src = "module M {\n func f() ;\n func g() { f() }\n}";
665 s.handle(&json!({
666 "jsonrpc": "2.0", "method": "textDocument/didOpen",
667 "params": { "textDocument": { "uri": "u", "text": src } }
668 }));
669 let out = s.handle(&json!({
670 "jsonrpc": "2.0", "id": 10, "method": "textDocument/references",
671 "params": { "textDocument": { "uri": "u" }, "position": { "line": 1, "character": 9 } }
672 }));
673 let locs = out[0]["result"].as_array().unwrap();
674 assert_eq!(locs.len(), 2);
676 assert!(locs.iter().any(|l| l["range"]["start"]["line"] == json!(2)));
677 }
678
679 #[test]
680 fn handle_completion_lists_symbols() {
681 let mut s = Server::new();
682 let src = "module M {\n func f() ;\n func g() { f() }\n}";
683 s.handle(&json!({
684 "jsonrpc": "2.0", "method": "textDocument/didOpen",
685 "params": { "textDocument": { "uri": "u", "text": src } }
686 }));
687 let out = s.handle(&json!({
688 "jsonrpc": "2.0", "id": 11, "method": "textDocument/completion",
689 "params": { "textDocument": { "uri": "u" } }
690 }));
691 let items = out[0]["result"].as_array().unwrap();
692 let labels: Vec<&str> = items.iter().map(|i| i["label"].as_str().unwrap()).collect();
693 assert!(labels.contains(&"f"));
694 assert!(labels.contains(&"g"));
695 }
696
697 #[test]
698 fn handle_inlay_hints_shows_routing_target() {
699 let mut s = Server::new();
700 let src = "module M {\n func f() ;\n}";
701 s.handle(&json!({
702 "jsonrpc": "2.0", "method": "textDocument/didOpen",
703 "params": { "textDocument": { "uri": "u", "text": src } }
704 }));
705 let out = s.handle(&json!({
706 "jsonrpc": "2.0", "id": 12, "method": "textDocument/inlayHint",
707 "params": { "textDocument": { "uri": "u" }, "range": { "start": { "line": 0, "character": 0 }, "end": { "line": 2, "character": 0 } } }
708 }));
709 let hints = out[0]["result"].as_array().unwrap();
710 assert!(!hints.is_empty());
711 assert!(hints
713 .iter()
714 .any(|h| h["label"].as_str().unwrap().contains("→")));
715 }
716}