1use std::collections::HashMap;
4
5use adam_lang::format_source;
6use lsp_server::{Connection, Message, Notification as ServerNotification, Request, Response};
7use lsp_types::{
8 DidChangeTextDocumentParams, DidOpenTextDocumentParams, DocumentFormattingParams, OneOf,
9 Position, PublishDiagnosticsParams, Range, ServerCapabilities, TextDocumentSyncCapability,
10 TextDocumentSyncKind, TextEdit, Uri,
11 notification::{
12 DidChangeTextDocument, DidOpenTextDocument, Notification as _, PublishDiagnostics,
13 },
14 request::{Formatting, Request as _},
15};
16
17use crate::modules::ModuleSources;
18
19const METHOD_NOT_FOUND: i32 = -32601;
21const INVALID_PARAMS: i32 = -32602;
24
25pub fn run() -> anyhow::Result<()> {
42 let (connection, io_threads) = Connection::stdio();
43 serve(&connection)?;
44 drop(connection);
45 io_threads.join()?;
46 Ok(())
47}
48
49pub fn serve(connection: &Connection) -> anyhow::Result<()> {
72 let capabilities = serde_json::to_value(ServerCapabilities {
73 text_document_sync: Some(TextDocumentSyncCapability::Kind(TextDocumentSyncKind::FULL)),
74 document_formatting_provider: Some(OneOf::Left(true)),
75 ..Default::default()
76 })?;
77 let options = connection.initialize(capabilities)?;
78 let modules = ModuleSources::from_initialization(
79 options
80 .get("initializationOptions")
81 .unwrap_or(&serde_json::Value::Null),
82 );
83 main_loop(connection, modules)
84}
85
86fn main_loop(connection: &Connection, mut modules: ModuleSources) -> anyhow::Result<()> {
95 let mut documents: HashMap<String, String> = HashMap::new();
96 for msg in &connection.receiver {
97 match msg {
98 Message::Request(req) => {
99 if connection.handle_shutdown(&req)? {
100 return Ok(());
101 }
102 handle_request(connection, &documents, req)?;
103 }
104 Message::Notification(not) => {
105 handle_notification(connection, &mut documents, &mut modules, not)?
106 }
107 Message::Response(_) => {}
108 }
109 }
110 Ok(())
111}
112
113fn handle_request(
124 connection: &Connection,
125 documents: &HashMap<String, String>,
126 req: Request,
127) -> anyhow::Result<()> {
128 match req.method.as_str() {
129 Formatting::METHOD => {
130 let id = req.id.clone();
131 match req.extract::<DocumentFormattingParams>(Formatting::METHOD) {
132 Ok((id, params)) => {
133 let edits = documents
137 .get(params.text_document.uri.as_str())
138 .map(|source| format_edits(source))
139 .unwrap_or_default();
140 connection
141 .sender
142 .send(Message::Response(Response::new_ok(id, edits)))?;
143 }
144 Err(error) => {
145 connection.sender.send(Message::Response(Response::new_err(
146 id,
147 INVALID_PARAMS,
148 error.to_string(),
149 )))?;
150 }
151 }
152 }
153 _ => {
154 let response = Response::new_err(
155 req.id.clone(),
156 METHOD_NOT_FOUND,
157 format!("unhandled method: {}", req.method),
158 );
159 connection.sender.send(Message::Response(response))?;
160 }
161 }
162 Ok(())
163}
164
165fn handle_notification(
180 connection: &Connection,
181 documents: &mut HashMap<String, String>,
182 modules: &mut ModuleSources,
183 not: ServerNotification,
184) -> anyhow::Result<()> {
185 match not.method.as_str() {
186 DidOpenTextDocument::METHOD => {
187 let params: DidOpenTextDocumentParams = match not.extract(DidOpenTextDocument::METHOD) {
188 Ok(params) => params,
189 Err(error) => {
190 eprintln!(
191 "adam-lsp: ignoring malformed {}: {error}",
192 DidOpenTextDocument::METHOD
193 );
194 return Ok(());
195 }
196 };
197 documents.insert(
198 params.text_document.uri.as_str().to_owned(),
199 params.text_document.text,
200 );
201 publish_all(connection, documents, modules)?;
202 }
203 DidChangeTextDocument::METHOD => {
204 let params: DidChangeTextDocumentParams =
205 match not.extract(DidChangeTextDocument::METHOD) {
206 Ok(params) => params,
207 Err(error) => {
208 eprintln!(
209 "adam-lsp: ignoring malformed {}: {error}",
210 DidChangeTextDocument::METHOD
211 );
212 return Ok(());
213 }
214 };
215 if params
216 .content_changes
217 .iter()
218 .any(|change| change.range.is_some() || change.range_length.is_some())
219 {
220 eprintln!("adam-lsp: ignoring incremental didChange with FULL synchronization");
221 return Ok(());
222 }
223 if let Some(change) = params.content_changes.into_iter().last() {
224 documents.insert(params.text_document.uri.as_str().to_owned(), change.text);
225 publish_all(connection, documents, modules)?;
226 }
227 }
228 "textDocument/didClose" => {
229 let params: lsp_types::DidCloseTextDocumentParams =
230 match serde_json::from_value(not.params) {
231 Ok(params) => params,
232 Err(error) => {
233 eprintln!("adam-lsp: ignoring malformed didClose: {error}");
234 return Ok(());
235 }
236 };
237 documents.remove(params.text_document.uri.as_str());
238 publish(connection, params.text_document.uri, Vec::new())?;
240 publish_all(connection, documents, modules)?;
241 }
242 "workspace/didChangeConfiguration" => {
243 let params: lsp_types::DidChangeConfigurationParams =
244 match serde_json::from_value(not.params) {
245 Ok(params) => params,
246 Err(error) => {
247 eprintln!("adam-lsp: ignoring malformed didChangeConfiguration: {error}");
248 return Ok(());
249 }
250 };
251 let old = modules.diagnostics(documents);
252 modules.configure(¶ms.settings);
253 let fresh = modules.diagnostics(documents);
254 for uri in old.keys().filter(|uri| !fresh.contains_key(*uri)) {
255 publish(connection, uri.parse()?, Vec::new())?;
256 }
257 publish_diagnostics(connection, fresh)?;
258 }
259 _ => {}
260 }
261 Ok(())
262}
263
264fn publish(
272 connection: &Connection,
273 uri: Uri,
274 diagnostics: Vec<lsp_types::Diagnostic>,
275) -> anyhow::Result<()> {
276 let params = PublishDiagnosticsParams {
277 uri,
278 diagnostics,
279 version: None,
280 };
281 let notification = ServerNotification::new(PublishDiagnostics::METHOD.to_string(), params);
282 connection
283 .sender
284 .send(Message::Notification(notification))?;
285 Ok(())
286}
287
288fn publish_all(
294 connection: &Connection,
295 documents: &HashMap<String, String>,
296 modules: &ModuleSources,
297) -> anyhow::Result<()> {
298 publish_diagnostics(connection, modules.diagnostics(documents))
299}
300
301fn publish_diagnostics(
308 connection: &Connection,
309 diagnostics: std::collections::BTreeMap<String, Vec<lsp_types::Diagnostic>>,
310) -> anyhow::Result<()> {
311 for (uri, diagnostics) in diagnostics {
312 publish(connection, uri.parse()?, diagnostics)?;
313 }
314 Ok(())
315}
316
317fn format_edits(source: &str) -> Vec<TextEdit> {
326 match format_source(source) {
327 Ok(formatted) => vec![TextEdit {
328 range: whole_document_range(),
329 new_text: formatted,
330 }],
331 Err(_) => Vec::new(),
332 }
333}
334
335fn whole_document_range() -> Range {
340 Range {
341 start: Position {
342 line: 0,
343 character: 0,
344 },
345 end: Position {
346 line: u32::MAX,
347 character: u32::MAX,
348 },
349 }
350}
351
352#[cfg(test)]
354mod tests {
355 use lsp_server::{Connection, Message, Notification as ServerNotification, Request, RequestId};
356 use lsp_types::{
357 DidChangeTextDocumentParams, DidOpenTextDocumentParams, DocumentFormattingParams,
358 PublishDiagnosticsParams, TextDocumentContentChangeEvent, TextDocumentIdentifier,
359 TextDocumentItem, TextEdit, VersionedTextDocumentIdentifier,
360 notification::{
361 DidChangeTextDocument, DidOpenTextDocument, Notification as _, PublishDiagnostics,
362 },
363 request::{Formatting, Request as _},
364 };
365
366 use super::{format_edits, serve};
367
368 #[test]
370 fn formatting_request_validates_params_and_unknown_document() {
371 let (server, client) = Connection::memory();
372 let documents = std::collections::HashMap::new();
373 for (params, valid) in [
374 (serde_json::json!({"missing":"params"}), false),
375 (
376 serde_json::json!({
377 "textDocument":{"uri":"file:///missing.adm2"},
378 "options":{"tabSize":4,"insertSpaces":true}
379 }),
380 true,
381 ),
382 ] {
383 super::handle_request(
384 &server,
385 &documents,
386 Request::new(4.into(), Formatting::METHOD.into(), params),
387 )
388 .unwrap();
389 let Message::Response(response) = client.receiver.recv().unwrap() else {
390 panic!("expected formatting response")
391 };
392 assert_eq!(response.id, 4.into());
393 if valid {
394 assert_eq!(response.response_result.unwrap(), serde_json::json!([]));
395 } else {
396 assert_eq!(
397 response.response_result.unwrap_err().code,
398 super::INVALID_PARAMS
399 );
400 }
401 }
402 }
403
404 #[test]
406 fn full_sync_rejects_range_changes_and_recovers() {
407 let (server, client) = Connection::memory();
408 let uri = "file:///full.adm2";
409 let original = "sheet old {}";
410 let mut documents = std::collections::HashMap::from([(uri.into(), original.into())]);
411 let mut modules = crate::modules::ModuleSources::default();
412 for changes in [
413 serde_json::json!([{"range":{"start":{"line":0,"character":0},"end":{"line":0,"character":1}},"text":"x"}]),
414 serde_json::json!([{"rangeLength":1,"text":"x"}]),
415 serde_json::json!([{"range":{"start":{"line":0,"character":0},"end":{"line":0,"character":1}},"text":"x"},{"text":"sheet new {}"}]),
416 serde_json::json!([]),
417 ] {
418 super::handle_notification(
419 &server,
420 &mut documents,
421 &mut modules,
422 ServerNotification::new(
423 DidChangeTextDocument::METHOD.into(),
424 serde_json::json!({"textDocument":{"uri":uri,"version":2},"contentChanges":changes}),
425 ),
426 ).unwrap();
427 assert_eq!(documents[uri], original);
428 assert!(client.receiver.try_recv().is_err());
429 }
430 super::handle_notification(
431 &server,
432 &mut documents,
433 &mut modules,
434 ServerNotification::new(
435 DidChangeTextDocument::METHOD.into(),
436 serde_json::json!({"textDocument":{"uri":uri,"version":3},"contentChanges":[{"text":"sheet interim {}"},{"text":"sheet new {}"}]}),
437 ),
438 ).unwrap();
439 assert_eq!(documents[uri], "sheet new {}");
440 let publication = expect_published(&client);
441 assert_eq!(publication.uri.as_str(), uri);
442 assert!(publication.diagnostics.is_empty());
443 }
444
445 #[test]
447 fn format_edits_preserve_closing_list_comments() {
448 let source = "sheet helper(a: i32 /* HEADER_BEFORE */) // HEADER_AFTER\n\
449 {} sheet app { relationship helper(a: x // CALL_BEFORE\n\
450 ) /* CALL_AFTER */; }";
451 let edits = format_edits(source);
452 assert_eq!(edits.len(), 1);
453 let formatted = &edits[0].new_text;
454 for marker in ["HEADER_BEFORE", "HEADER_AFTER", "CALL_BEFORE", "CALL_AFTER"] {
455 assert_eq!(formatted.matches(marker).count(), 1, "{formatted}");
456 }
457 assert_eq!(format_edits(formatted)[0].new_text, *formatted);
458 }
459
460 #[test]
462 fn format_edits_preserve_complete_modules_and_refuse_recovered_items() {
463 let source = "use lib::pair as p; sheet helper(a:f64){} sheet app { cell x:f64; relationship p(a:x); }";
464 let edits = format_edits(source);
465 assert_eq!(edits.len(), 1);
466 let formatted = &edits[0].new_text;
467 assert!(formatted.contains("use lib::pair as p;"), "{formatted}");
468 assert!(formatted.contains("helper(a: f64)"), "{formatted}");
469 assert!(formatted.contains("p(a: x)"), "{formatted}");
470 assert_eq!(format_edits(formatted)[0].new_text, *formatted);
471 for malformed in [
472 "use lib::; sheet good {}",
473 "sheet helper(a: ) {} sheet app {}",
474 "sheet helper(a: i32,) {} sheet app {}",
475 "sheet app { relationship helper(a: x,); }",
476 "sheet good {} sheet bad { cell : i32; }",
477 ] {
478 assert!(format_edits(malformed).is_empty(), "{malformed}");
479 }
480 }
481
482 #[test]
484 fn format_edits_is_empty_for_a_syntax_error() {
485 assert!(format_edits("not a sheet at all").is_empty());
486 }
487
488 #[test]
490 fn format_edits_is_empty_for_a_recovered_syntax_error() {
491 assert!(format_edits("sheet s { cell x unknown_syntax }").is_empty());
492 }
493
494 #[test]
496 fn format_edits_returns_one_edit_replacing_the_whole_document() {
497 let edits = format_edits("sheet s{cell x:i32=1;}");
498 assert_eq!(edits.len(), 1);
499 assert_eq!(edits[0].range.start, lsp_types::Position::new(0, 0));
500 assert!(edits[0].range.end.line >= 1);
501 assert_eq!(edits[0].new_text, "sheet s {\n cell x: i32 = 1;\n}\n");
502 }
503
504 #[test]
506 fn format_edits_formats_a_cell_with_a_filter() {
507 let edits = format_edits("sheet s { cell a:i32=1 filter _; }");
508 assert_eq!(edits.len(), 1);
509 assert_eq!(
510 edits[0].new_text,
511 "sheet s {\n cell a: i32 = 1 filter _;\n}\n"
512 );
513 }
514
515 #[test]
517 fn format_edits_formats_a_cell_with_a_range_inclusive_filter() {
518 let edits = format_edits("sheet s { cell a:i32=0 filter 0..=200; }");
524 assert_eq!(edits.len(), 1);
525 assert_eq!(
526 edits[0].new_text,
527 "sheet s {\n cell a: i32 = 0 filter 0..=200;\n}\n"
528 );
529 }
530
531 #[test]
533 fn formatting_request_returns_the_edit_for_a_previously_opened_document() {
534 let (server, client) = Connection::memory();
535 let server_thread = std::thread::spawn(move || serve(&server));
536 initialize(&client);
537
538 let uri: lsp_types::Uri = "file:///test.adm2".parse().unwrap();
539 client
540 .sender
541 .send(Message::Notification(ServerNotification::new(
542 DidOpenTextDocument::METHOD.to_string(),
543 DidOpenTextDocumentParams {
544 text_document: TextDocumentItem {
545 uri: uri.clone(),
546 language_id: "adam-lang".to_string(),
547 version: 1,
548 text: "sheet s { cell x: i32 = 1; }".to_string(),
549 },
550 },
551 )))
552 .unwrap();
553 expect_published(&client); client
556 .sender
557 .send(Message::Request(Request::new(
558 RequestId::from(3),
559 Formatting::METHOD.to_string(),
560 DocumentFormattingParams {
561 text_document: TextDocumentIdentifier { uri: uri.clone() },
562 options: lsp_types::FormattingOptions {
563 tab_size: 4,
564 insert_spaces: true,
565 ..Default::default()
566 },
567 work_done_progress_params: Default::default(),
568 },
569 )))
570 .unwrap();
571 let response = match client.receiver.recv().unwrap() {
572 Message::Response(r) => r,
573 other => panic!("expected a response, got {other:?}"),
574 };
575 assert_eq!(response.id, RequestId::from(3));
576 let edits: Vec<TextEdit> =
577 serde_json::from_value(response.response_result.unwrap()).unwrap();
578 assert_eq!(edits.len(), 1);
579 assert_eq!(edits[0].new_text, "sheet s {\n cell x: i32 = 1;\n}\n");
580
581 shut_down(&client);
582 server_thread.join().unwrap().unwrap();
583 }
584
585 fn initialize(client: &Connection) {
589 client
590 .sender
591 .send(Message::Request(Request::new(
592 RequestId::from(1),
593 "initialize".to_string(),
594 serde_json::json!({}),
595 )))
596 .unwrap();
597 let Message::Response(response) = client.receiver.recv().unwrap() else {
598 panic!("expected initialization response")
599 };
600 assert_eq!(response.id, RequestId::from(1));
601 let result = response.response_result.unwrap();
602 assert_eq!(result["capabilities"]["textDocumentSync"], 1);
603 client
604 .sender
605 .send(Message::Notification(ServerNotification::new(
606 "initialized".to_string(),
607 serde_json::json!({}),
608 )))
609 .unwrap();
610 }
611
612 fn shut_down(client: &Connection) {
614 client
615 .sender
616 .send(Message::Request(Request::new(
617 RequestId::from(2),
618 "shutdown".to_string(),
619 serde_json::json!(null),
620 )))
621 .unwrap();
622 let Message::Response(response) = client.receiver.recv().unwrap() else {
623 panic!("expected shutdown response")
624 };
625 assert_eq!(response.id, RequestId::from(2));
626 assert!(response.response_result.is_ok(), "{response:?}");
627 client
628 .sender
629 .send(Message::Notification(ServerNotification::new(
630 "exit".to_string(),
631 serde_json::json!(null),
632 )))
633 .unwrap();
634 }
635
636 fn expect_published(client: &Connection) -> PublishDiagnosticsParams {
641 let published = match client.receiver.recv().unwrap() {
642 Message::Notification(n) => n,
643 other => panic!("expected a notification, got {other:?}"),
644 };
645 assert_eq!(published.method, PublishDiagnostics::METHOD);
646 serde_json::from_value(published.params).unwrap()
647 }
648
649 #[test]
651 fn open_notification_triggers_a_publish_diagnostics_notification() {
652 let (server, client) = Connection::memory();
653 let server_thread = std::thread::spawn(move || serve(&server));
654 initialize(&client);
655
656 let uri: lsp_types::Uri = "file:///test.pm".parse().unwrap();
657 client
658 .sender
659 .send(Message::Notification(ServerNotification::new(
660 DidOpenTextDocument::METHOD.to_string(),
661 DidOpenTextDocumentParams {
662 text_document: TextDocumentItem {
663 uri: uri.clone(),
664 language_id: "adam-lang".to_string(),
665 version: 1,
666 text: "sheet s { cell x: i32 = 1.0; }".to_string(),
667 },
668 },
669 )))
670 .unwrap();
671
672 let params = expect_published(&client);
673 assert_eq!(params.uri, uri);
674 assert_eq!(params.diagnostics.len(), 1);
675
676 shut_down(&client);
677 server_thread.join().unwrap().unwrap();
678 }
679
680 #[test]
682 fn malformed_open_notification_is_skipped_not_crashed() {
683 let (server, client) = Connection::memory();
684 let server_thread = std::thread::spawn(move || serve(&server));
685 initialize(&client);
686
687 client
689 .sender
690 .send(Message::Notification(ServerNotification::new(
691 DidOpenTextDocument::METHOD.to_string(),
692 serde_json::json!({"not": "valid"}),
693 )))
694 .unwrap();
695
696 let uri: lsp_types::Uri = "file:///test.pm".parse().unwrap();
699 client
700 .sender
701 .send(Message::Notification(ServerNotification::new(
702 DidOpenTextDocument::METHOD.to_string(),
703 DidOpenTextDocumentParams {
704 text_document: TextDocumentItem {
705 uri: uri.clone(),
706 language_id: "adam-lang".to_string(),
707 version: 1,
708 text: "sheet s { cell x: i32 = 1; }".to_string(),
709 },
710 },
711 )))
712 .unwrap();
713
714 let params = expect_published(&client);
715 assert_eq!(params.uri, uri);
716 assert!(params.diagnostics.is_empty());
717
718 shut_down(&client);
719 server_thread.join().unwrap().unwrap();
720 }
721
722 #[test]
724 fn change_notification_after_open_triggers_a_second_publish_diagnostics_notification() {
725 let (server, client) = Connection::memory();
726 let server_thread = std::thread::spawn(move || serve(&server));
727 initialize(&client);
728
729 let uri: lsp_types::Uri = "file:///test.pm".parse().unwrap();
730 client
731 .sender
732 .send(Message::Notification(ServerNotification::new(
733 DidOpenTextDocument::METHOD.to_string(),
734 DidOpenTextDocumentParams {
735 text_document: TextDocumentItem {
736 uri: uri.clone(),
737 language_id: "adam-lang".to_string(),
738 version: 1,
739 text: "sheet s { cell x: i32 = 1; }".to_string(),
740 },
741 },
742 )))
743 .unwrap();
744 let first = expect_published(&client);
745 assert!(first.diagnostics.is_empty());
746
747 client
748 .sender
749 .send(Message::Notification(ServerNotification::new(
750 DidChangeTextDocument::METHOD.to_string(),
751 DidChangeTextDocumentParams {
752 text_document: VersionedTextDocumentIdentifier {
753 uri: uri.clone(),
754 version: 2,
755 },
756 content_changes: vec![TextDocumentContentChangeEvent {
757 range: None,
758 range_length: None,
759 text: "sheet s { cell x: i32 = 1.0; }".to_string(),
760 }],
761 },
762 )))
763 .unwrap();
764 let second = expect_published(&client);
765 assert_eq!(second.uri, uri);
766 assert_eq!(second.diagnostics.len(), 1);
767
768 shut_down(&client);
769 server_thread.join().unwrap().unwrap();
770 }
771
772 #[test]
774 fn unrecognized_request_method_gets_a_method_not_found_response() {
775 let (server, client) = Connection::memory();
776 let server_thread = std::thread::spawn(move || serve(&server));
777 initialize(&client);
778
779 client
780 .sender
781 .send(Message::Request(Request::new(
782 RequestId::from(3),
783 "textDocument/hover".to_string(),
784 serde_json::json!({}),
785 )))
786 .unwrap();
787
788 let response = match client.receiver.recv().unwrap() {
789 Message::Response(r) => r,
790 other => panic!("expected a response, got {other:?}"),
791 };
792 assert_eq!(response.id, RequestId::from(3));
793 assert_eq!(
794 response.response_result.unwrap_err().code,
795 super::METHOD_NOT_FOUND
796 );
797
798 shut_down(&client);
799 server_thread.join().unwrap().unwrap();
800 }
801}