Skip to main content

adam_lsp/
dispatch.rs

1//! Wires `lsp-server` to the explicit module and source-only diagnostic hosts.
2
3use 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
19/// The JSON-RPC "Method not found" error code, reused by LSP for unhandled request methods.
20const METHOD_NOT_FOUND: i32 = -32601;
21/// The JSON-RPC "Invalid params" error code, used when `textDocument/formatting`'s params fail
22/// to deserialize.
23const INVALID_PARAMS: i32 = -32602;
24
25/// Runs the adam-lang language server on stdin/stdout until the client sends `exit`.
26///
27/// - Complexity: cumulative message dispatch, source analysis and serialization
28///   time; space for the current source snapshot and its analysis.
29///
30/// # Errors
31///
32/// Returns `Err` if the initialize handshake fails, a message can't be read from or written to
33/// stdio, or the background reader/writer threads panic.
34///
35/// # Examples
36///
37/// ```no_run
38/// adam_lsp::run()?;
39/// # Ok::<(), anyhow::Error>(())
40/// ```
41pub 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
49/// Performs initialization, then publishes source/module diagnostics until shutdown.
50///
51/// Reads the caller-owned `moduleSources` wire snapshot described in the
52/// [crate documentation](crate), and accepts complete configuration replacements.
53///
54/// Exposed separately from [`run`] so tests can drive an in-memory [`Connection::memory`] pair
55/// instead of real stdio.
56///
57/// # Errors
58///
59/// Returns an error if initialization, shutdown or transport communication fails.
60///
61/// - Complexity: cumulative message dispatch, source analysis and serialization
62///   time; space for the current source snapshot and its analysis.
63///
64/// # Examples
65///
66/// ```no_run
67/// let (server, _client) = lsp_server::Connection::memory();
68/// adam_lsp::serve(&server)?;
69/// # Ok::<(), anyhow::Error>(())
70/// ```
71pub 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
86/// Dispatches every message on `connection` until a `shutdown`/`exit` sequence ends the server.
87///
88/// - Complexity: cumulative dispatch and analysis time; space for the current
89///   source snapshot and its analysis.
90///
91/// # Errors
92///
93/// Returns `Err` if a message can't be read from or sent to `connection` (a broken transport).
94fn 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
113/// Handles one client request. Only `textDocument/formatting` is implemented; every other method
114/// gets a JSON-RPC "Method not found" response (`shutdown` is intercepted earlier, in
115/// `main_loop`, and never reaches here).
116///
117/// - Complexity: formatting time/space for an open source, plus response
118///   serialization and expected O(u) URI lookup time for u URI bytes.
119///
120/// # Errors
121///
122/// Returns `Err` only if sending the response fails (a broken transport).
123fn 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                    // A URI not present in `documents` (never seen via didOpen/didChange) silently
134                    // gets no edits, the same "nothing to do" response as a syntax error — not an error
135                    // response.
136                    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
165/// Applies document/configuration changes and republishes all affected source owners.
166///
167/// Open documents overlay registered revisions by exact URI; closing restores the
168/// supplied revision. Malformed notifications leave documents unchanged.
169/// FULL-sync changes must omit both range fields; any range-bearing entry
170/// rejects the complete batch. Complete replacements apply in array order.
171/// - Complexity: diagnostic analysis and serialization plus O(n) full-text storage.
172///
173/// # Errors
174///
175/// Returns `Err` only if sending the resulting `publishDiagnostics` notification fails (a broken
176/// transport). A `didOpen`/`didChange` notification whose params fail to deserialize is logged to
177/// stderr and skipped rather than propagated, so one malformed client message can't take down the
178/// server.
179fn 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            // Clear stale source-only diagnostics; module publications below replace this.
239            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(&params.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
264/// Sends one complete diagnostic replacement for `uri`.
265///
266/// - Complexity: O(u + d) time and space for u URI and d serialized diagnostic bytes.
267///
268/// # Errors
269///
270/// Returns `Err` if sending the notification on `connection` fails (a broken transport).
271fn 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
288/// Rechecks all supplied and open sources and publishes clean/error replacements.
289///
290/// - Complexity: the source snapshot's analysis cost plus diagnostic serialization.
291/// # Errors
292/// Returns an error if the transport fails.
293fn 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
301/// Sends a complete diagnostic replacement for each URI in the supplied map.
302///
303/// - Complexity: O(f + u + d) time and O(u + d) serialization space for f
304///   owners, u URI bytes and d diagnostic bytes.
305/// # Errors
306/// Returns an error if the transport fails or an internal URI cannot be parsed.
307fn 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
317/// Computes the `textDocument/formatting` edit for adam-lang `source`.
318///
319/// - Postcondition: returns an empty `Vec` if [`format_source`] refuses `source` (it doesn't
320///   parse, or parses with any recovered syntax error) — refusing to format code it can't fully
321///   understand, matching `rustfmt`. Otherwise returns exactly one [`TextEdit`] replacing the
322///   whole document with `format_source`'s output.
323/// - Complexity: [`format_source`]'s parsing/trivia/formatting costs and O(o)
324///   output space for o formatted bytes, with no caching across calls.
325fn 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
335/// A `Range` guaranteed to cover an entire document regardless of its actual length — LSP
336/// clients clamp an out-of-bounds end position to the document's real end, so this avoids
337/// needing to compute the exact last line/column of `source` (and getting it wrong for the
338/// common trailing-newline edge case).
339fn 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/// Verifies formatting, lifecycle handshakes and safe notification dispatch.
353#[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    /// Rejects malformed formatting parameters and returns no edits for unknown documents.
369    #[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    /// Rejects incremental FULL-sync messages without losing the last complete document.
405    #[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    /// Whole-document edits preserve comments around list closers without trailing commas.
446    #[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    /// Module formatting preserves imports, aliases, parameter types and named bindings.
461    #[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    /// Refuses formatting a source without a sheet.
483    #[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    /// Refuses formatting a sheet with a recovered malformed declaration.
489    #[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    /// Produces one canonical full-document replacement for a clean sheet.
495    #[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    /// Preserves a cell filter in canonical formatting.
505    #[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    /// Formats inclusive range filters without failing the request.
516    #[test]
517    fn format_edits_formats_a_cell_with_a_range_inclusive_filter() {
518        // Regression test: formatting a range-literal filter (as in
519        // begin/examples/inequality.adm2's `filter 0..=200`) used to panic inside
520        // cel_parser::fmt::binary_op_level ("unknown operator `range_inclusive`"), crashing
521        // adam-lsp's single-threaded server mid-request — which VS Code's format-on-save then
522        // waited on forever, indistinguishable from a hang.
523        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    /// Formats the stored source of an opened document over the real transport.
532    #[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); // the didOpen's diagnostics notification
554
555        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    /// Completes initialization after verifying its successful response ID and FULL sync.
586    ///
587    /// - Complexity: O(n) space for the initialization response's n payload bytes.
588    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    /// Sends exit after verifying the successful shutdown response ID.
613    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    /// Receives the next message from `client` and asserts it's a `publishDiagnostics`
637    /// notification, returning its deserialized params.
638    ///
639    /// - Complexity: O(n) time and space for n serialized diagnostic bytes.
640    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    /// Publishes the opened owner's type errors.
650    #[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    /// Continues serving after a malformed open notification.
681    #[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        // Params that don't deserialize as `DidOpenTextDocumentParams` at all.
688        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        // A subsequent well-formed `didOpen` still gets a normal `publishDiagnostics` response,
697        // proving the server is still alive and serving requests after the malformed message.
698        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    /// Replaces clean diagnostics after a complete text update introduces a type error.
723    #[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    /// Returns method-not-found with the original ID for unsupported requests.
773    #[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}