//! One end-to-end smoke test: spawn the real binary and speak framed //! JSON-RPC at it over stdio. //! //! Everything else in this crate is tested by calling handlers directly with //! constructed state, which is faster and pins behavior more precisely. This //! test exists to catch the things those cannot: that the binary starts, that //! the `Content-Length` framing works in both directions, that the //! initialize/initialized/shutdown/exit handshake completes, and that a //! notification the server *pushes* (diagnostics) actually reaches the wire. //! //! The framing is hand-rolled here on purpose โ€” a test that reused the //! server's own transport could not catch a framing bug. use std::io::{BufRead, BufReader, Write}; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; /// Frame one JSON payload the way LSP wants it. fn frame(payload: &str) -> String { format!("Content-Length: {}\r\n\r\n{payload}", payload.len()) } /// Split a stdout dump into its JSON payloads. fn unframe(mut input: impl BufRead) -> Vec { let mut out = Vec::new(); while let Some(message) = read_message(&mut input) { out.push(message); } out } /// One framed message, or `None` when the stream ends or goes wrong. fn read_message(input: &mut impl BufRead) -> Option { let mut length = None; // Headers, terminated by an empty line. loop { let mut line = String::new(); if input.read_line(&mut line).unwrap_or(0) == 0 { return None; } let trimmed = line.trim_end_matches(['\r', '\n']); if trimmed.is_empty() { break; } if let Some(value) = trimmed.strip_prefix("Content-Length: ") { length = value.parse::().ok(); } } let mut body = vec![0u8; length?]; input.read_exact(&mut body).ok()?; serde_json::from_slice(&body).ok() } fn temp_dir(name: &str) -> PathBuf { let dir = std::env::temp_dir().join(format!("lucisv_server_e2e_{}_{name}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).expect("temp dir"); dir } /// Write a whole session to the server and read everything it says back. /// /// Writing before reading is what keeps this from deadlocking: the server /// processes the messages in order and exits on `exit`, so stdout closes and /// the read terminates on its own. fn talk(session: &str) -> Vec { let mut child = Command::new(env!("CARGO_BIN_EXE_lucisv-server")) .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::null()) .spawn() .expect("the server binary starts"); child.stdin.take().expect("stdin").write_all(session.as_bytes()).expect("write session"); let stdout = child.stdout.take().expect("stdout"); let messages = unframe(BufReader::new(stdout)); let status = child.wait().expect("the server exits"); assert!(status.success(), "clean exit, got {status:?}"); messages } /// An `initialize` + `didOpen` + one `textDocument/formatting` + shutdown /// session against a scratch workspace holding `config` as its `lucisv.toml`. /// The client asks for a 2-space indent, which is what an editor default /// looks like. fn format_session(dir: &Path, file: &Path, ids: &[u32]) -> Vec { let root = format!("file://{}", dir.display()); let uri = format!("file://{}", file.display()); let source = std::fs::read_to_string(file).expect("read source"); let mut session = vec![ frame(&format!( r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"# )), frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), frame(&format!( r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, serde_json::to_string(&source).expect("json") )), ]; for id in ids { session.push(frame(&format!( r#"{{"jsonrpc":"2.0","id":{id},"method":"textDocument/formatting","params":{{"textDocument":{{"uri":"{uri}"}},"options":{{"tabSize":2,"insertSpaces":true}}}}}}"# ))); } session.push(frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#)); session.push(frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#)); talk(&session.concat()) } /// The one edit a formatting response carries. fn new_text(messages: &[serde_json::Value], id: u32) -> String { let response = messages .iter() .find(|m| m["id"] == id) .unwrap_or_else(|| panic!("no formatting response in {messages:#?}")); let edits = response["result"].as_array().expect("an array of edits"); assert_eq!(edits.len(), 1, "one whole-document edit, got {edits:#?}"); edits[0]["newText"].as_str().expect("newText").to_string() } const UNFORMATTED: &str = "module m;\nwire a;\nendmodule\n"; #[test] fn a_lucisv_toml_governs_formatting_over_the_editors_tab_size() { let dir = temp_dir("config"); std::fs::write(dir.join("lucisv.toml"), "indent = 4\n").expect("write config"); let file = dir.join("m.sv"); std::fs::write(&file, UNFORMATTED).expect("write"); let messages = format_session(&dir, &file, &[2]); assert_eq!( new_text(&messages, 2), "module m;\n wire a;\nendmodule\n", "the config's indent=4 beats the client's tabSize=2" ); assert!( !messages.iter().any(|m| m["method"] == "window/showMessage"), "a good config says nothing: {messages:#?}" ); let _ = std::fs::remove_dir_all(&dir); } #[test] fn a_broken_lucisv_toml_warns_once_and_still_formats() { let dir = temp_dir("brokenconfig"); std::fs::write(dir.join("lucisv.toml"), "indent = 4\nbogus = 1\n").expect("write config"); let file = dir.join("m.sv"); std::fs::write(&file, UNFORMATTED).expect("write"); // Two formatting requests, no edit in between: the warning is said once. let messages = format_session(&dir, &file, &[2, 3]); for id in [2, 3] { assert_eq!( new_text(&messages, id), "module m;\n wire a;\nendmodule\n", "formatting proceeds with the built-in defaults, never fails" ); } let warnings: Vec<_> = messages.iter().filter(|m| m["method"] == "window/showMessage").collect(); assert_eq!(warnings.len(), 1, "once per file change, got {warnings:#?}"); assert_eq!(warnings[0]["params"]["type"], 2, "a warning, not an error"); let text = warnings[0]["params"]["message"].as_str().expect("a message"); assert!(text.contains("unknown key `bogus`"), "{text}"); assert!(text.contains("lucisv.toml:2"), "the message names file and line: {text}"); let _ = std::fs::remove_dir_all(&dir); } /// A UTF-16 boundary in the buffer: the emoji line is two lines above the one /// the range names, so a byte-vs-UTF-16 confusion would format the wrong item. const MULTI_BYTE: &str = "module m;\n // รฉ โœ“ ๐ŸŽ‰ note\n wire a;\n wire b;\nendmodule\n"; #[test] fn range_formatting_is_advertised_and_formats_only_the_selection() { let dir = temp_dir("rangefmt"); let file = dir.join("m.sv"); std::fs::write(&file, MULTI_BYTE).expect("write"); let root = format!("file://{}", dir.display()); let uri = format!("file://{}", file.display()); let request = |id: u32, sl: u32, sc: u32, el: u32, ec: u32| { frame(&format!( r#"{{"jsonrpc":"2.0","id":{id},"method":"textDocument/rangeFormatting","params":{{"textDocument":{{"uri":"{uri}"}},"range":{{"start":{{"line":{sl},"character":{sc}}},"end":{{"line":{el},"character":{ec}}}}},"options":{{"tabSize":2,"insertSpaces":true}}}}}}"# )) }; let session = [ frame(&format!( r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"# )), frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), frame(&format!( r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, serde_json::to_string(MULTI_BYTE).expect("json") )), // "Select line 3", the way an editor sends it: end at the start of 4. request(2, 2, 0, 3, 0), // A cursor on `endmodule`, which is already written as lucisv writes it. request(3, 4, 0, 4, 9), request(4, 0, 0, 99, 0), // A cursor on the emoji comment: a leading comment belongs to its // item's unit, so the declaration under it is what gets laid out. request(5, 1, 8, 1, 8), frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), ] .concat(); let messages = talk(&session); let initialize = messages.iter().find(|m| m["id"] == 1).expect("initialize response"); assert_eq!( initialize["result"]["capabilities"]["documentRangeFormattingProvider"], serde_json::json!(true), "the capability must be advertised now that --lines exists" ); assert_eq!( new_text(&messages, 2), "module m;\n // รฉ โœ“ ๐ŸŽ‰ note\n wire a;\n wire b;\nendmodule\n", "only the selected line, and the emoji survives" ); let idle = messages.iter().find(|m| m["id"] == 3).expect("response"); assert_eq!(idle["result"].as_array().expect("an array").len(), 0, "nothing to change"); assert_eq!( new_text(&messages, 5), "module m;\n // รฉ โœ“ ๐ŸŽ‰ note\n wire a;\n wire b;\nendmodule\n", "a leading comment selects the item it belongs to" ); assert_eq!( new_text(&messages, 4), "module m;\n // รฉ โœ“ ๐ŸŽ‰ note\n wire a;\n wire b;\nendmodule\n", "a range over the whole buffer is a whole-file format" ); let _ = std::fs::remove_dir_all(&dir); } /// A file with a tab (`no-tabs`, Safe fix) and a trailing space /// (`no-trailing-whitespace`, Safe fix) โ€” and a name matching its module, so /// `module-filename` stays quiet and every finding here is fixable. const VIOLATING: &str = "module lint_me;\n\twire a;\n wire b; \nendmodule\n"; #[test] fn lint_diagnostics_and_a_code_action_round_trip_over_the_wire() { let dir = temp_dir("lint"); let file = dir.join("lint_me.sv"); std::fs::write(&file, VIOLATING).expect("write"); let root = format!("file://{}", dir.display()); let uri = format!("file://{}", file.display()); let session = [ frame(&format!( r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"# )), frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), frame(&format!( r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, serde_json::to_string(VIOLATING).expect("json") )), // Every action for the whole file. frame(&format!( r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/codeAction","params":{{"textDocument":{{"uri":"{uri}"}},"range":{{"start":{{"line":0,"character":0}},"end":{{"line":3,"character":0}}}},"context":{{"diagnostics":[]}}}}}}"# )), // And the fix-on-save request an editor sends: one kind only. frame(&format!( r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/codeAction","params":{{"textDocument":{{"uri":"{uri}"}},"range":{{"start":{{"line":0,"character":0}},"end":{{"line":3,"character":0}}}},"context":{{"diagnostics":[],"only":["source.fixAll.lucisv"]}}}}}}"# )), frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), ] .concat(); let messages = talk(&session); // 1. The capability was advertised with both kinds. let initialize = messages.iter().find(|m| m["id"] == 1).expect("initialize response"); let kinds = &initialize["result"]["capabilities"]["codeActionProvider"]["codeActionKinds"]; let kinds = kinds.as_array().expect("the kinds are listed, not just `true`"); assert!(kinds.iter().any(|k| k == "quickfix"), "{kinds:#?}"); assert!(kinds.iter().any(|k| k == "source.fixAll.lucisv"), "{kinds:#?}"); // 2. Exactly one publish for this version, carrying both lint findings. let published: Vec<_> = messages.iter().filter(|m| m["method"] == "textDocument/publishDiagnostics").collect(); assert_eq!(published.len(), 1, "one publish replaces, two would flicker: {published:#?}"); let diagnostics = published[0]["params"]["diagnostics"].as_array().expect("an array"); assert_eq!(diagnostics.len(), 2, "{diagnostics:#?}"); let codes: Vec<&str> = diagnostics.iter().filter_map(|d| d["code"].as_str()).collect(); assert!(codes.contains(&"no-tabs"), "{codes:?}"); assert!(codes.contains(&"no-trailing-whitespace"), "{codes:?}"); for diagnostic in diagnostics { assert_eq!(diagnostic["severity"], 2, "a lint finding is a warning"); assert_eq!(diagnostic["source"], "lucisv"); } // 3. Two quick fixes and one fixAll, and the quick fixes name the finding. let actions = messages.iter().find(|m| m["id"] == 2).expect("code action response"); let actions = actions["result"].as_array().expect("an array of actions"); let quick: Vec<_> = actions.iter().filter(|a| a["kind"] == "quickfix").collect(); assert_eq!(quick.len(), 2, "{actions:#?}"); assert_eq!(quick[0]["diagnostics"].as_array().expect("its diagnostic").len(), 1); let all: Vec<_> = actions.iter().filter(|a| a["kind"] == "source.fixAll.lucisv").collect(); assert_eq!(all.len(), 1, "{actions:#?}"); // 4. The filtered request returns the fixAll action and nothing else, and // its edit is the whole document with every Safe fix applied. let filtered = messages.iter().find(|m| m["id"] == 3).expect("filtered response"); let filtered = filtered["result"].as_array().expect("an array"); assert_eq!(filtered.len(), 1, "only what was asked for: {filtered:#?}"); let edits = filtered[0]["edit"]["changes"][uri.as_str()].as_array().expect("edits"); assert_eq!(edits.len(), 1, "one whole-document edit"); assert_eq!( edits[0]["newText"], "module lint_me;\n wire a;\n wire b;\nendmodule\n", "the linter's own fixed output" ); let _ = std::fs::remove_dir_all(&dir); } /// A fenced tab and an unfenced one, in a file whose name matches its module. /// One pass converges here (no two fixes want the same bytes), which is what /// makes the server's single-pass `fixAll` comparable to the CLI's loop. const FENCED: &str = "module fenced;\n// lucisv: off\n\twire a;\n// lucisv: on\n\twire b;\nendmodule\n"; /// The `lucisv` CLI binary, built beside this crate's own. /// /// Cargo names no env var for another package's binary, so it is found by /// path. `cargo test --workspace` โ€” the gate this test belongs to โ€” always /// builds it; `cargo test -p lucisv_server` alone may not, and the test says so /// and passes rather than failing for a reason that is not about the server. fn lucisv_binary() -> Option { let path = Path::new(env!("CARGO_BIN_EXE_lucisv-server")).with_file_name("lucisv"); path.is_file().then_some(path) } #[test] fn fix_all_edits_exactly_what_lucisv_check_fix_edits_inside_a_fence() { let Some(lucisv) = lucisv_binary() else { eprintln!("skipped: the `lucisv` binary is not built next to `lucisv-server`"); return; }; let dir = temp_dir("fence"); let file = dir.join("fenced.sv"); std::fs::write(&file, FENCED).expect("write"); let root = format!("file://{}", dir.display()); let uri = format!("file://{}", file.display()); let session = [ frame(&format!( r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"# )), frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), frame(&format!( r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, serde_json::to_string(FENCED).expect("json") )), // Fix-on-save, then a cursor sitting on the fenced tab. frame(&format!( r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/codeAction","params":{{"textDocument":{{"uri":"{uri}"}},"range":{{"start":{{"line":0,"character":0}},"end":{{"line":5,"character":0}}}},"context":{{"diagnostics":[],"only":["source.fixAll.lucisv"]}}}}}}"# )), frame(&format!( r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/codeAction","params":{{"textDocument":{{"uri":"{uri}"}},"range":{{"start":{{"line":2,"character":0}},"end":{{"line":2,"character":1}}}},"context":{{"diagnostics":[]}}}}}}"# )), frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), ] .concat(); let messages = talk(&session); // Both tabs are still reported: `off` withholds the fix, not the finding. let published = messages .iter() .find(|m| m["method"] == "textDocument/publishDiagnostics") .expect("diagnostics"); let diagnostics = published["params"]["diagnostics"].as_array().expect("an array"); assert_eq!(diagnostics.len(), 2, "one per tab, fenced included: {diagnostics:#?}"); // No quick fix on the fenced line. let at_fence = messages.iter().find(|m| m["id"] == 3).expect("code action response"); let at_fence = at_fence["result"].as_array().expect("an array"); assert!( !at_fence.iter().any(|a| a["kind"] == "quickfix"), "no lightbulb inside a fence: {at_fence:#?}" ); // And `fixAll` writes exactly what `lucisv check --fix` writes. let fix_all = messages.iter().find(|m| m["id"] == 2).expect("fixAll response"); let fix_all = fix_all["result"].as_array().expect("an array"); assert_eq!(fix_all.len(), 1, "only what was asked for: {fix_all:#?}"); let edits = fix_all[0]["edit"]["changes"][uri.as_str()].as_array().expect("edits"); assert_eq!(edits.len(), 1, "one whole-document edit"); let fixed = edits[0]["newText"].as_str().expect("newText").to_string(); let cli = dir.join("cli.sv"); std::fs::write(&cli, FENCED).expect("write"); let status = Command::new(&lucisv) .arg("check") .arg("--fix") .arg(&cli) .stdout(Stdio::null()) .stderr(Stdio::null()) .status() .expect("the lucisv binary runs"); // Two findings remain (the fenced tab is reported and unfixed), so the // CLI exits 1 โ€” the documented "reported, never auto-fixed" contract. assert_eq!(status.code(), Some(1), "violations remain, and that is correct"); let cli_output = std::fs::read_to_string(&cli).expect("read back"); assert_eq!(fixed, cli_output, "the two front ends agree byte for byte"); assert!(cli_output.contains("\twire a;"), "the fenced tab survived: {cli_output:?}"); assert!(cli_output.contains(" wire b;"), "the free tab was fixed: {cli_output:?}"); let _ = std::fs::remove_dir_all(&dir); } /// A buffer that is broken *and* still has a resolvable reference: error /// recovery is what makes both true at once, and the LSP depends on it. const SOURCE: &str = "module top;\n wire a;\n assign a = 1;\n wire ;\nendmodule\n"; #[test] fn the_binary_serves_a_whole_session_over_stdio() { let dir = temp_dir("session"); let file = dir.join("top.sv"); std::fs::write(&file, SOURCE).expect("write"); let root = format!("file://{}", dir.display()); let uri = format!("file://{}", file.display()); // Every message is written before anything is read: the server processes // them in order and exits on `exit`, so stdout closes and the test can // never deadlock waiting on a message that is not coming. let session = [ frame(&format!( r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"# )), frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), frame(&format!( r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, serde_json::to_string(SOURCE).expect("json") )), // The `a` of `assign a` โ€” line 2, character 9. frame(&format!( r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/definition","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":2,"character":9}}}}}}"# )), frame(r#"{"jsonrpc":"2.0","id":3,"method":"shutdown","params":null}"#), frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), ] .concat(); let messages = talk(&session); // 1. The initialize response advertises what we implement. let initialize = messages .iter() .find(|m| m["id"] == 1) .unwrap_or_else(|| panic!("no initialize response in {messages:#?}")); let capabilities = &initialize["result"]["capabilities"]; assert_eq!(capabilities["positionEncoding"], "utf-16"); assert_eq!(capabilities["documentFormattingProvider"], true); assert_eq!(capabilities["definitionProvider"], true); assert!(capabilities["semanticTokensProvider"].is_object()); assert_eq!(initialize["result"]["serverInfo"]["name"], "lucisv-server"); // 2. Diagnostics were pushed for the broken buffer. let published = messages .iter() .find(|m| m["method"] == "textDocument/publishDiagnostics") .unwrap_or_else(|| panic!("no diagnostics in {messages:#?}")); assert_eq!(published["params"]["uri"], uri.as_str()); let diagnostics = published["params"]["diagnostics"].as_array().expect("an array"); assert_eq!(diagnostics.len(), 1, "one error for `wire ;`"); assert_eq!(diagnostics[0]["severity"], 1, "an error"); assert_eq!(diagnostics[0]["source"], "lucisv"); assert_eq!(diagnostics[0]["range"]["start"]["line"], 3, "the `wire ;` line"); // 3. Definition jumped to the declaration, in the same file. let definition = messages .iter() .find(|m| m["id"] == 2) .unwrap_or_else(|| panic!("no definition response in {messages:#?}")); let locations = definition["result"].as_array().expect("an array of locations"); assert_eq!(locations.len(), 1, "got {locations:#?}"); assert_eq!(locations[0]["uri"], uri.as_str()); assert_eq!(locations[0]["range"]["start"]["line"], 1, "the `wire a;` line"); assert_eq!(locations[0]["range"]["start"]["character"], 7); // 4. Shutdown was acknowledged. let shutdown = messages .iter() .find(|m| m["id"] == 3) .unwrap_or_else(|| panic!("no shutdown response in {messages:#?}")); assert!(shutdown["error"].is_null(), "shutdown must succeed"); let _ = std::fs::remove_dir_all(&dir); } /// Nested blocks, plus a `begin` that never closes. Both halves of the scope /// feature have something to say about this buffer: `documentHighlight` pairs /// the two `end`s that *are* closed, and the missing-closer warning points at /// the `initial begin` on line 1 rather than at the `endmodule` the parser /// choked on. const UNBALANCED: &str = "module m;\n initial begin\n if (x) begin\n y = 1;\n end\nendmodule\n"; /// The same file with the missing `end` put back โ€” the other half of the /// `unmatched` contract: present and empty rather than absent. const BALANCED: &str = "module m;\n initial begin\n if (x) begin\n y = 1;\n end\n end\nendmodule\n"; #[test] fn scope_highlights_and_the_missing_end_warning_round_trip_over_the_wire() { let dir = temp_dir("scopes"); let file = dir.join("m.sv"); std::fs::write(&file, UNBALANCED).expect("write"); let clean_file = dir.join("clean.sv"); std::fs::write(&clean_file, BALANCED).expect("write"); let root = format!("file://{}", dir.display()); let uri = format!("file://{}", file.display()); let clean_uri = format!("file://{}", clean_file.display()); let highlight = |id: u32, line: u32, character: u32| { frame(&format!( r#"{{"jsonrpc":"2.0","id":{id},"method":"textDocument/documentHighlight","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":{line},"character":{character}}}}}}}"# )) }; let session = [ frame(&format!( r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"# )), frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), frame(&format!( r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, serde_json::to_string(UNBALANCED).expect("json") )), // The inner `begin` on line 2, which does close. highlight(2, 2, 11), // The `end` on line 4, the other half of that same pair. highlight(3, 4, 4), // The unclosed `begin` on line 1: no pair, so no answer. highlight(4, 1, 10), // Not a keyword at all. highlight(5, 3, 6), // The rainbow's data source โ€” a custom method, so this is the only // thing that proves the request loop routes it at all. frame(&format!( r#"{{"jsonrpc":"2.0","id":6,"method":"lucisv/scopePairs","params":{{"textDocument":{{"uri":"{uri}"}}}}}}"# )), // The same request against a balanced buffer: `unmatched` has to come // back present and empty, because that is what clears the extension's // error decoration. frame(&format!( r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{clean_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, serde_json::to_string(BALANCED).expect("json") )), frame(&format!( r#"{{"jsonrpc":"2.0","id":7,"method":"lucisv/scopePairs","params":{{"textDocument":{{"uri":"{clean_uri}"}}}}}}"# )), frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), ] .concat(); let messages = talk(&session); let initialize = messages.iter().find(|m| m["id"] == 1).expect("initialize response"); assert_eq!( initialize["result"]["capabilities"]["documentHighlightProvider"], serde_json::json!(true), "the capability must be advertised" ); let ranges = |id: u32| -> Vec<(u64, u64)> { let response = messages .iter() .find(|m| m["id"] == id) .unwrap_or_else(|| panic!("no response {id} in {messages:#?}")); response["result"] .as_array() .unwrap_or_else(|| panic!("response {id} is not a list: {response:#?}")) .iter() .map(|h| { ( h["range"]["start"]["line"].as_u64().expect("line"), h["range"]["start"]["character"].as_u64().expect("character"), ) }) .collect() }; assert_eq!(ranges(2), vec![(2, 11), (4, 4)], "the inner begin pairs with the inner end"); assert_eq!(ranges(3), vec![(2, 11), (4, 4)], "and the end pairs back"); for id in [4, 5] { let response = messages.iter().find(|m| m["id"] == id).expect("a response"); assert!(response["error"].is_null(), "declining is not an error: {response:#?}"); assert!( response["result"].is_null(), "must be null so the editor keeps its word highlighting, got {response:#?}" ); } // Only the pair that actually closed is offered for colouring. Its depth // counts the enclosing scopes the rainbow *draws* โ€” the still-open outer // `begin`, but not the `module` around it. let scope_pairs = messages.iter().find(|m| m["id"] == 6).expect("scopePairs response"); assert!(scope_pairs["error"].is_null(), "the method must be routed: {scope_pairs:#?}"); let pairs = scope_pairs["result"]["pairs"].as_array().expect("a pairs array"); assert_eq!(pairs.len(), 1, "the unclosed begin has nothing to colour: {pairs:#?}"); assert_eq!(pairs[0]["depth"], 1); assert_eq!(pairs[0]["open"]["start"]["line"], 2); assert_eq!(pairs[0]["close"]["start"]["line"], 4); // The `begin` that lost its `end` is reported so the extension can paint // it in its error colour instead of leaving it undecorated. let unmatched = scope_pairs["result"]["unmatched"].as_array().expect("an unmatched array"); assert_eq!(unmatched.len(), 1, "the unclosed begin on line 1: {unmatched:#?}"); assert_eq!(unmatched[0]["start"]["line"], 1); assert_eq!(unmatched[0]["start"]["character"], 10); let clean = messages.iter().find(|m| m["id"] == 7).expect("scopePairs response"); assert_eq!(clean["result"]["pairs"].as_array().map(Vec::len), Some(2), "{clean:#?}"); assert_eq!( clean["result"]["unmatched"].as_array().map(Vec::len), Some(0), "a balanced buffer answers with an empty list, not a missing field: {clean:#?}" ); // The warning rides along with the parse error, in one publish. let published = messages .iter() .find(|m| m["method"] == "textDocument/publishDiagnostics") .expect("diagnostics"); let diagnostics = published["params"]["diagnostics"].as_array().expect("an array"); let warning = diagnostics .iter() .find(|d| d["severity"] == 2) .unwrap_or_else(|| panic!("no warning in {diagnostics:#?}")); assert_eq!(warning["message"], "`begin` has no matching `end` โ€” is an `end` missing?"); assert_eq!(warning["range"]["start"]["line"], 1, "the `initial begin`"); assert_eq!(warning["range"]["start"]["character"], 10); assert_eq!(warning["source"], "lucisv"); assert!( diagnostics.iter().any(|d| d["severity"] == 1), "the parse error it explains is still there" ); let _ = std::fs::remove_dir_all(&dir); } /// One unindented item, so the indent the server chose is visible in the edit. const UNINDENTED: &str = "module settings_me;\nwire a;\nendmodule\n"; #[test] fn pushed_settings_reach_the_formatter_and_can_change_mid_session() { let dir = temp_dir("settings"); let file = dir.join("settings_me.sv"); std::fs::write(&file, UNINDENTED).expect("write"); let root = format!("file://{}", dir.display()); let uri = format!("file://{}", file.display()); // Every format asks for a 2-space tab, so anything else in the answer came // from the pushed settings. let format = |id: u32| { frame(&format!( r#"{{"jsonrpc":"2.0","id":{id},"method":"textDocument/formatting","params":{{"textDocument":{{"uri":"{uri}"}},"options":{{"tabSize":2,"insertSpaces":true}}}}}}"# )) }; let push = |indent: &str| { frame(&format!( r#"{{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{{"settings":{{"lucisv":{{"serverPath":"lucisv-server","rainbowBeginEnd":true,"lineLength":null,"indent":{indent},"exclude":[]}}}}}}}}"# )) }; let session = [ frame(&format!( r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"# )), frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), frame(&format!( r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, serde_json::to_string(UNINDENTED).expect("json") )), // Nothing pushed yet: the editor's tab size is the best signal there is. format(2), // The initial push a client makes on startup. push("4"), format(3), // The user changes their mind mid-session โ€” no restart, no reload. push("8"), format(4), // And clears the setting again, handing the tab size back. push("null"), format(5), // A payload that is nonsense must be ignored, not honoured by halves. frame(r#"{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{"settings":{"lucisv":{"indent":"four","lineLength":9999}}}}"#), format(6), frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), ] .concat(); let messages = talk(&session); assert_eq!(new_text(&messages, 2), "module settings_me;\n wire a;\nendmodule\n", "tab size"); assert_eq!(new_text(&messages, 3), "module settings_me;\n wire a;\nendmodule\n", "pushed 4"); assert_eq!( new_text(&messages, 4), "module settings_me;\n wire a;\nendmodule\n", "a mid-session change takes effect on the next request, with no restart" ); assert_eq!( new_text(&messages, 5), "module settings_me;\n wire a;\nendmodule\n", "clearing the setting hands the tab size back" ); assert_eq!( new_text(&messages, 6), "module settings_me;\n wire a;\nendmodule\n", "a wrong-typed indent and an out-of-range width are both ignored" ); let _ = std::fs::remove_dir_all(&dir); } #[test] fn the_save_hook_is_advertised_and_formats_only_when_it_is_asked_to() { // The one thing a unit test cannot check: that the capability really // reaches the wire, and that a client's `formatOnSave` push really turns // the hook on for the requests that follow it. let dir = temp_dir("willsave"); let file = dir.join("m.sv"); std::fs::write(&file, UNINDENTED).expect("write"); let root = format!("file://{}", dir.display()); let uri = format!("file://{}", file.display()); let will_save = |id: u32| { frame(&format!( r#"{{"jsonrpc":"2.0","id":{id},"method":"textDocument/willSaveWaitUntil","params":{{"textDocument":{{"uri":"{uri}"}},"reason":1}}}}"# )) }; let formatted = "module settings_me;\n wire a;\nendmodule\n"; let session = [ frame(&format!( r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"# )), frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), frame(&format!( r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, serde_json::to_string(UNINDENTED).expect("json") )), // Nothing pushed: the hook declines, so a client that never opted in // saves exactly what it was going to save. will_save(2), frame(r#"{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{"settings":{"lucisv":{"formatOnSave":true}}}}"#), will_save(3), // The client applies the edit and writes; the buffer it now holds is // what the next save asks about. frame(&format!( r#"{{"jsonrpc":"2.0","method":"textDocument/didChange","params":{{"textDocument":{{"uri":"{uri}","version":2}},"contentChanges":[{{"text":{}}}]}}}}"#, serde_json::to_string(formatted).expect("json") )), will_save(4), frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), ] .concat(); let messages = talk(&session); let initialize = messages.iter().find(|m| m["id"] == 1).expect("initialize response"); let sync = &initialize["result"]["capabilities"]["textDocumentSync"]; assert_eq!(sync["willSaveWaitUntil"], true, "the hook is advertised: {sync:#?}"); assert!(sync.get("willSave").is_none(), "the notification is not: {sync:#?}"); let declined = messages.iter().find(|m| m["id"] == 2).expect("a response to the first save"); assert!(declined["result"].is_null(), "off by default: {declined:#?}"); assert_eq!(new_text(&messages, 3), formatted, "the push turns it on for the next save"); let again = messages.iter().find(|m| m["id"] == 4).expect("a response to the third save"); assert_eq!( again["result"].as_array().expect("an array of edits").len(), 0, "a formatted buffer saves with no edits at all: {again:#?}" ); assert!( !messages.iter().any(|m| m["method"] == "window/showMessage"), "nothing went wrong, so nothing was said: {messages:#?}" ); let _ = std::fs::remove_dir_all(&dir); } #[test] fn a_pushed_exclude_rebuilds_the_index_mid_session() { // The one link a unit test cannot check: that the notification handler // actually re-scans. `state.rs` proves the scan honours `exclude` and that // a change asks for a rescan; only the wire shows that `server.rs` asks. let dir = temp_dir("exclude"); std::fs::create_dir_all(dir.join("scratch")).expect("subdir"); std::fs::write(dir.join("kept.sv"), "package kept_pkg;\n localparam K = 1;\nendpackage\n") .expect("write"); std::fs::write( dir.join("scratch/wip.sv"), "package scratch_pkg;\n localparam K = 1;\nendpackage\n", ) .expect("write"); let root = format!("file://{}", dir.display()); let query = |id: u32, name: &str| { frame(&format!( r#"{{"jsonrpc":"2.0","id":{id},"method":"workspace/symbol","params":{{"query":"{name}"}}}}"# )) }; let exclude = |patterns: &str| { frame(&format!( r#"{{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{{"settings":{{"lucisv":{{"exclude":{patterns}}}}}}}}}"# )) }; // An open buffer, so the *republish* half of `reindex()` has somewhere to // land โ€” `didSave` and the exclude push share that code, and without an // open document the loop it runs is empty and proves nothing. let open_uri = format!("file://{}", dir.join("kept.sv").display()); let source = std::fs::read_to_string(dir.join("kept.sv")).expect("read"); let session = [ frame(&format!( r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"# )), frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), // Publish #1. frame(&format!( r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{open_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, serde_json::to_string(&source).expect("json") )), query(2, "scratch_pkg"), // A real change: rescan, and publish #2. exclude(r#"["scratch"]"#), query(3, "scratch_pkg"), query(4, "kept_pkg"), // The same value again is not a change: no rescan, and no publish. exclude(r#"["scratch"]"#), query(5, "scratch_pkg"), // Clearing it puts the file back โ€” the rescan runs in both directions, // and publishes #3. exclude("[]"), query(6, "scratch_pkg"), frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), ] .concat(); let messages = talk(&session); let hits = |id: u32| -> usize { let response = messages .iter() .find(|m| m["id"] == id) .unwrap_or_else(|| panic!("no response {id} in {messages:#?}")); response["result"].as_array().map_or(0, |a| a.len()) }; assert_eq!(hits(2), 1, "premise: indexed before the push"); assert_eq!(hits(3), 0, "the pushed exclude took it out of the index"); assert_eq!(hits(4), 1, "and left the file it does not match alone"); assert_eq!(hits(5), 0, "re-pushing the same value changes nothing"); assert_eq!(hits(6), 1, "clearing the setting puts it back"); // The other half of `reindex()`: every open buffer is republished against // the new index. One publish for the `didOpen`, then one per *changed* // exclude โ€” and none for the push that changed nothing. let publishes = messages .iter() .filter(|m| m["method"] == "textDocument/publishDiagnostics") .filter(|m| m["params"]["uri"] == open_uri.as_str()) .count(); assert_eq!(publishes, 3, "didOpen + two changed excludes, in {messages:#?}"); let _ = std::fs::remove_dir_all(&dir); } #[test] fn a_pushed_filelist_narrows_the_index_mid_session_and_reports_a_bad_one() { // The filelist's whole promise on the wire: a file that is in the tree but // not in the project stops being indexed the moment the setting arrives, // and a path that cannot be read says so instead of emptying the index. let dir = temp_dir("filelist"); std::fs::create_dir_all(dir.join("rtl")).expect("subdir"); std::fs::write(dir.join("rtl/a.sv"), "package a_pkg;\n localparam K = 1;\nendpackage\n") .expect("write"); std::fs::write(dir.join("rtl/b.sv"), "package b_pkg;\n localparam K = 1;\nendpackage\n") .expect("write"); std::fs::write(dir.join("files.f"), "// only a\nrtl/a.sv\n").expect("write"); let root = format!("file://{}", dir.display()); let query = |id: u32, name: &str| { frame(&format!( r#"{{"jsonrpc":"2.0","id":{id},"method":"workspace/symbol","params":{{"query":"{name}"}}}}"# )) }; let filelist = |path: &str| { frame(&format!( r#"{{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{{"settings":{{"lucisv":{{"filelist":"{path}"}}}}}}}}"# )) }; let session = [ frame(&format!( r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"# )), frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), query(2, "b_pkg"), filelist("files.f"), query(3, "b_pkg"), query(4, "a_pkg"), // A path that does not exist: the walk answers instead, and the user // is told why rather than left with an empty index. filelist("typo.f"), query(5, "b_pkg"), // Clearing it hands the workspace walk back. filelist(""), query(6, "b_pkg"), frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), ] .concat(); let messages = talk(&session); let hits = |id: u32| -> usize { let response = messages .iter() .find(|m| m["id"] == id) .unwrap_or_else(|| panic!("no response {id} in {messages:#?}")); response["result"].as_array().map_or(0, |a| a.len()) }; assert_eq!(hits(2), 1, "premise: the walk indexes both files"); assert_eq!(hits(3), 0, "the filelist does not name b.sv, so it is not indexed"); assert_eq!(hits(4), 1, "and the file it does name still is"); assert_eq!(hits(5), 1, "an unreadable filelist falls back to the walk"); assert_eq!(hits(6), 1, "clearing the setting hands the walk back"); let complained = messages.iter().filter(|m| m["method"] == "window/showMessage").any(|m| { let text = m["params"]["message"].as_str().unwrap_or_default(); text.contains("typo.f") && text.contains("indexing the workspace instead") }); assert!(complained, "the unreadable filelist must be reported, in {messages:#?}"); let _ = std::fs::remove_dir_all(&dir); } #[test] fn with_no_workspace_folder_the_open_files_own_directory_is_indexed() { // A single file opened with no folder: the scope is what sits beside it, // and the index has to be built on `didOpen` rather than on the first save. let dir = temp_dir("noroot"); std::fs::create_dir_all(dir.join("rtl/deeper")).expect("subdir"); std::fs::write(dir.join("rtl/open.sv"), "package open_pkg;\n localparam K = 1;\nendpackage\n") .expect("write"); std::fs::write( dir.join("rtl/sibling.sv"), "package sibling_pkg;\n localparam K = 1;\nendpackage\n", ) .expect("write"); std::fs::write( dir.join("rtl/deeper/below.sv"), "package below_pkg;\n localparam K = 1;\nendpackage\n", ) .expect("write"); let open_uri = format!("file://{}", dir.join("rtl/open.sv").display()); let source = std::fs::read_to_string(dir.join("rtl/open.sv")).expect("read"); let query = |id: u32, name: &str| { frame(&format!( r#"{{"jsonrpc":"2.0","id":{id},"method":"workspace/symbol","params":{{"query":"{name}"}}}}"# )) }; let session = [ // No `rootUri` and no `workspaceFolders`: the single-file case. frame( r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"processId":null,"capabilities":{}}}"#, ), frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), query(2, "sibling_pkg"), frame(&format!( r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{open_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, serde_json::to_string(&source).expect("json") )), query(3, "sibling_pkg"), query(4, "below_pkg"), frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), ] .concat(); let messages = talk(&session); let hits = |id: u32| -> usize { let response = messages .iter() .find(|m| m["id"] == id) .unwrap_or_else(|| panic!("no response {id} in {messages:#?}")); response["result"].as_array().map_or(0, |a| a.len()) }; assert_eq!(hits(2), 0, "premise: nothing is indexed before a file is open"); assert_eq!(hits(3), 1, "the neighbour of the open file is indexed"); assert_eq!(hits(4), 0, "but the walk does not descend โ€” this is one directory"); let _ = std::fs::remove_dir_all(&dir); } /// The two files a cross-file rename needs: a module and something that /// instantiates it, with a macro of the same name so the warning path runs too. const RENAME_SUB: &str = "`define sub 1\nmodule sub (input logic clk);\nendmodule\n"; const RENAME_TOP: &str = "module top;\n sub u_sub (.clk(1'b0));\nendmodule\n"; #[test] fn prepare_rename_and_rename_round_trip_over_the_wire() { let dir = temp_dir("rename"); std::fs::write(dir.join("sub.sv"), RENAME_SUB).expect("write"); let top = dir.join("top.sv"); std::fs::write(&top, RENAME_TOP).expect("write"); let root = format!("file://{}", dir.display()); let uri = format!("file://{}", top.display()); let sub_uri = format!("file://{}", dir.join("sub.sv").display()); // Line 1, character 2 is the `sub` of the instantiation. let at = |id: u32, method: &str, extra: &str| { frame(&format!( r#"{{"jsonrpc":"2.0","id":{id},"method":"textDocument/{method}","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":1,"character":2}}{extra}}}}}"# )) }; let session = [ frame(&format!( r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"# )), frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), frame(&format!( r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, serde_json::to_string(RENAME_TOP).expect("json") )), at(2, "prepareRename", ""), at(3, "rename", r#","newName":"child""#), // A keyword is refused, and the editor is told why. at(4, "rename", r#","newName":"module""#), // `module` on line 0 is not a symbol: prepareRename must decline so // the editor never opens its box. frame(&format!( r#"{{"jsonrpc":"2.0","id":5,"method":"textDocument/prepareRename","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":0,"character":1}}}}}}"# )), frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), ] .concat(); let messages = talk(&session); let initialize = messages.iter().find(|m| m["id"] == 1).expect("initialize response"); let rename_provider = &initialize["result"]["capabilities"]["renameProvider"]; assert_eq!(rename_provider["prepareProvider"], serde_json::json!(true), "{rename_provider:#?}"); let prepared = messages.iter().find(|m| m["id"] == 2).expect("prepareRename response"); assert_eq!(prepared["result"]["placeholder"], "sub"); assert_eq!(prepared["result"]["range"]["start"]["character"], 2); assert_eq!(prepared["result"]["range"]["end"]["character"], 5); let renamed = messages.iter().find(|m| m["id"] == 3).expect("rename response"); let changes = &renamed["result"]["changes"]; assert_eq!(changes.as_object().expect("a changes map").len(), 2, "{changes:#?}"); assert_eq!(changes[&uri][0]["newText"], "child"); assert_eq!(changes[&uri][0]["range"]["start"]["line"], 1); assert_eq!(changes[&sub_uri][0]["newText"], "child"); assert_eq!(changes[&sub_uri][0]["range"]["start"]["line"], 1, "the module declaration"); assert_eq!(changes[&sub_uri][0]["range"]["start"]["character"], 7); assert_eq!( changes[&sub_uri].as_array().expect("one edit").len(), 1, "the `define of the same name is never edited" ); // And it is reported rather than passed over in silence. assert!( messages.iter().any(|m| m["method"] == "window/logMessage" && m["params"]["message"].as_str().is_some_and(|s| s.contains("macro"))), "the macro warning must reach the client: {messages:#?}" ); let refused = messages.iter().find(|m| m["id"] == 4).expect("refusal response"); assert_eq!(refused["error"]["code"], -32803, "LSP's RequestFailed"); assert!( refused["error"]["message"].as_str().is_some_and(|m| m.contains("keyword")), "{refused:#?}" ); assert!(refused["result"].is_null(), "a refusal carries no edits: {refused:#?}"); let declined = messages.iter().find(|m| m["id"] == 5).expect("prepareRename response"); assert_eq!(declined["error"]["code"], -32803); assert!( declined["error"]["message"].as_str().is_some_and(|m| m.contains("no symbol to rename")), "{declined:#?}" ); let _ = std::fs::remove_dir_all(&dir); } /// A module and one instantiation of it, for the port refactorings. const PORTS_SUB: &str = "module sub (\n input logic clk,\n input logic rst\n);\nendmodule\n"; /// QA's reproduction: a port list whose last port lives in an `` `ifdef `` arm. const PORTS_COND: &str = "module cond (\n input clk\n`ifdef HAS_RST\n , input rst\n`endif\n);\nendmodule\n"; const PORTS_TOP: &str = "module top;\n logic clk, rst, cfg;\n sub u_sub (.clk(clk));\nendmodule\n"; #[test] fn a_port_code_action_and_the_port_commands_round_trip_over_the_wire() { // What only an e2e test can check: that the command is advertised, that // `workspace/executeCommand` reaches the engine with its arguments intact, // and that a code action carries a cross-file `WorkspaceEdit` of its own. let dir = temp_dir("ports"); let sub = dir.join("sub.sv"); std::fs::write(&sub, PORTS_SUB).expect("write"); let top = dir.join("top.sv"); std::fs::write(&top, PORTS_TOP).expect("write"); let cond = dir.join("cond.sv"); std::fs::write(&cond, PORTS_COND).expect("write"); let root = format!("file://{}", dir.display()); let top_uri = format!("file://{}", top.display()); let sub_uri = format!("file://{}", sub.display()); let cond_uri = format!("file://{}", cond.display()); let open = |uri: &str, text: &str| { frame(&format!( r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, serde_json::to_string(text).expect("json") )) }; let session = [ frame(&format!( r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"# )), frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), open(&top_uri, PORTS_TOP), open(&sub_uri, PORTS_SUB), open(&cond_uri, PORTS_COND), // The cursor on `u_sub`: the instantiation is missing `.rst`. frame(&format!( r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/codeAction","params":{{"textDocument":{{"uri":"{top_uri}"}},"range":{{"start":{{"line":2,"character":6}},"end":{{"line":2,"character":6}}}},"context":{{"diagnostics":[]}}}}}}"# )), // `lucisv.propagatePorts` at the same place, through the command. frame(&format!( r#"{{"jsonrpc":"2.0","id":3,"method":"workspace/executeCommand","params":{{"command":"lucisv.propagatePorts","arguments":["{top_uri}",{{"line":2,"character":6}}]}}}}"# )), // `lucisv.addPort` โ€” the one that needs text nobody can click. frame(&format!( r#"{{"jsonrpc":"2.0","id":4,"method":"workspace/executeCommand","params":{{"command":"lucisv.addPort","arguments":["{top_uri}","sub","input logic cfg"]}}}}"# )), // ...and a declaration that is not one is refused with a sentence. frame(&format!( r#"{{"jsonrpc":"2.0","id":5,"method":"workspace/executeCommand","params":{{"command":"lucisv.addPort","arguments":["{top_uri}","sub","wire"]}}}}"# )), // ...and a port that would land inside an `ifdef arm is refused, over // the wire, not only in the crate's own tests. frame(&format!( r#"{{"jsonrpc":"2.0","id":6,"method":"workspace/executeCommand","params":{{"command":"lucisv.addPort","arguments":["{cond_uri}","cond","input logic cfg"]}}}}"# )), frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), ] .concat(); let messages = talk(&session); // 1. The commands are advertised, and so is the code-action kind. let initialize = messages.iter().find(|m| m["id"] == 1).expect("initialize response"); let capabilities = &initialize["result"]["capabilities"]; let commands = capabilities["executeCommandProvider"]["commands"] .as_array() .unwrap_or_else(|| panic!("no executeCommandProvider in {capabilities:#?}")); assert!(commands.iter().any(|c| c == "lucisv.addPort"), "{commands:#?}"); assert!(commands.iter().any(|c| c == "lucisv.removePort"), "{commands:#?}"); assert!(commands.iter().any(|c| c == "lucisv.propagatePorts"), "{commands:#?}"); let kinds = capabilities["codeActionProvider"]["codeActionKinds"] .as_array() .expect("the kinds are listed"); assert!(kinds.iter().any(|k| k == "refactor.rewrite.lucisv.ports"), "{kinds:#?}"); // 2. The code action carries its own edit, ready to apply. let actions = messages.iter().find(|m| m["id"] == 2).expect("codeAction response"); let offered = actions["result"].as_array().expect("an array of actions"); let port_action = offered .iter() .find(|a| a["kind"] == "refactor.rewrite.lucisv.ports") .unwrap_or_else(|| panic!("no port action in {offered:#?}")); assert_eq!(port_action["title"], "lucisv: connect 1 missing port"); let edits = port_action["edit"]["changes"][&top_uri].as_array().expect("one file's edits"); assert_eq!(edits.len(), 1); assert_eq!(edits[0]["newText"], ", .rst(rst)"); assert_eq!(edits[0]["range"]["start"]["line"], 2); // 3. The command answers with the same edit. let propagated = messages.iter().find(|m| m["id"] == 3).expect("executeCommand response"); let edits = propagated["result"]["changes"][&top_uri].as_array().expect("edits"); assert_eq!(edits[0]["newText"], ", .rst(rst)"); // 4. `addPort` reaches both files. let added = messages.iter().find(|m| m["id"] == 4).expect("executeCommand response"); let changes = &added["result"]["changes"]; assert_eq!(changes.as_object().expect("a changes map").len(), 2, "{changes:#?}"); assert_eq!(changes[&sub_uri][0]["newText"], ",\n input logic cfg"); assert_eq!(changes[&top_uri][0]["newText"], ", .cfg(cfg)"); // 5. A refusal is `RequestFailed` with the engine's own sentence. let refused = messages.iter().find(|m| m["id"] == 5).expect("refusal response"); assert_eq!(refused["error"]["code"], -32803, "LSP's RequestFailed"); assert!( refused["error"]["message"] .as_str() .is_some_and(|m| m.contains("not a single ANSI port declaration")), "{refused:#?}" ); // 6. ...and so is a port that would be conditionally compiled. let conditional = messages.iter().find(|m| m["id"] == 6).expect("refusal response"); assert_eq!(conditional["error"]["code"], -32803); assert!( conditional["error"]["message"] .as_str() .is_some_and(|m| m.contains("conditionally compiled") && m.contains("`ifdef HAS_RST")), "{conditional:#?}" ); assert!(conditional["result"].is_null(), "a refusal carries no edits: {conditional:#?}"); let _ = std::fs::remove_dir_all(&dir); } /// The module hinting pair: a definition worth a skeleton, and a top that is /// half-way through instantiating it. const HINT_SUB: &str = "module hint_sub #(\n parameter int WIDTH = 8\n) (\n input logic clk,\n input logic [WIDTH-1:0] data,\n output logic ready\n);\nendmodule\n"; /// `clk` is declared, `data` and `ready` are not โ€” so one port auto-connects /// and two do not. Line 2 is the half-typed module name. const HINT_TOP: &str = "module hint_top;\n logic clk;\n hint_s\nendmodule\n"; #[test] fn completion_and_signature_help_round_trip_over_the_wire() { // What only an e2e test can check: that both capabilities are advertised // with the shapes a client reads, that the snippet flag the client sent at // `initialize` is the one the item comes back with, and that the // skeleton survives JSON encoding with its tabstops intact. let dir = temp_dir("hint"); let sub = dir.join("hint_sub.sv"); std::fs::write(&sub, HINT_SUB).expect("write"); let top = dir.join("hint_top.sv"); std::fs::write(&top, HINT_TOP).expect("write"); let root = format!("file://{}", dir.display()); let top_uri = format!("file://{}", top.display()); // A connection list being typed, as a `didChange` so the buffer really is // half-written when signature help is asked for. let typing = "module hint_top;\n logic clk;\n hint_sub u_hint_sub (.clk(clk), .data(\nendmodule\n"; let session = [ frame(&format!( r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{"textDocument":{{"completion":{{"completionItem":{{"snippetSupport":true}}}}}}}}}}}}"# )), frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), frame(&format!( r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{top_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, serde_json::to_string(HINT_TOP).expect("json") )), // The cursor at the end of ` hint_s` on line 2. frame(&format!( r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/completion","params":{{"textDocument":{{"uri":"{top_uri}"}},"position":{{"line":2,"character":8}}}}}}"# )), // ...and inside the `always` block, where nothing may be offered. frame(&format!( r#"{{"jsonrpc":"2.0","method":"textDocument/didChange","params":{{"textDocument":{{"uri":"{top_uri}","version":2}},"contentChanges":[{{"text":{}}}]}}}}"#, serde_json::to_string( "module hint_top;\n always_comb begin\n hint_s\n end\nendmodule\n" ) .expect("json") )), frame(&format!( r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/completion","params":{{"textDocument":{{"uri":"{top_uri}"}},"position":{{"line":2,"character":10}}}}}}"# )), // Now a half-typed connection list, and signature help inside it. frame(&format!( r#"{{"jsonrpc":"2.0","method":"textDocument/didChange","params":{{"textDocument":{{"uri":"{top_uri}","version":3}},"contentChanges":[{{"text":{}}}]}}}}"#, serde_json::to_string(typing).expect("json") )), frame(&format!( r#"{{"jsonrpc":"2.0","id":4,"method":"textDocument/signatureHelp","params":{{"textDocument":{{"uri":"{top_uri}"}},"position":{{"line":2,"character":38}}}}}}"# )), frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), ] .concat(); let messages = talk(&session); // 1. Both capabilities are advertised, with the trigger characters the // signature-help handler actually answers on. let initialize = messages.iter().find(|m| m["id"] == 1).expect("initialize response"); let capabilities = &initialize["result"]["capabilities"]; assert!(capabilities["completionProvider"].is_object(), "{capabilities:#?}"); let triggers = capabilities["signatureHelpProvider"]["triggerCharacters"] .as_array() .unwrap_or_else(|| panic!("no signatureHelpProvider in {capabilities:#?}")); assert_eq!(triggers, &["(", ","]); // 2. The module item, first of its tier, inserting the whole skeleton as // a snippet โ€” and keywords beside it, in a later tier. let completion = messages.iter().find(|m| m["id"] == 2).expect("completion response"); let items = completion["result"]["items"] .as_array() .unwrap_or_else(|| panic!("no completion list in {completion:#?}")); let skeletons: Vec<&serde_json::Value> = items .iter() .filter(|item| item["sortText"].as_str().is_some_and(|s| s.starts_with('0'))) .collect(); assert_eq!(skeletons.len(), 1, "{items:#?}"); let item = skeletons[0]; assert_eq!(item["label"], "hint_sub"); assert_eq!(item["kind"], 9, "CompletionItemKind.Module"); assert_eq!(item["insertTextFormat"], 2, "InsertTextFormat.Snippet"); let new_text = item["textEdit"]["newText"].as_str().expect("newText"); assert_eq!( new_text, "hint_sub #(\n .WIDTH(${1:8})\n ) ${2:u_hint_sub} (\n .clk(clk),\n .data(${3:data}),\n .ready(${4:ready})\n );", "`clk` is in scope and binds itself; the rest are tabstops" ); assert_eq!(item["textEdit"]["range"]["start"]["character"], 2, "the typed word is replaced"); assert_eq!(item["textEdit"]["range"]["end"]["character"], 8); // The skeleton already carries the site's indentation on every line but // the first, so the client is told to leave it alone (`InsertTextMode.asIs`). assert_eq!(item["insertTextMode"], 1, "InsertTextMode.asIs: {item:#?}"); // `hint_s` also prefixes no keyword, but `clk` is in scope and the file's // own words are there, so the general tiers really did run. assert!( items.iter().any(|i| i["sortText"].as_str().is_some_and(|s| !s.starts_with('0'))), "the general tiers answer at the same position: {items:#?}" ); // 3. Inside an `always_comb` there is no *module* item to complete โ€” but // keywords and project names still are. let inside = messages.iter().find(|m| m["id"] == 3).expect("completion response"); let inside_items = inside["result"]["items"] .as_array() .unwrap_or_else(|| panic!("no completion list in {inside:#?}")); assert!( !inside_items.iter().any(|i| i["sortText"].as_str().is_some_and(|s| s.starts_with('0'))), "no skeleton belongs in a procedural block: {inside_items:#?}" ); // 4. Signature help names the ports and points at the one being connected. let help = messages.iter().find(|m| m["id"] == 4).expect("signatureHelp response"); let signatures = help["result"]["signatures"] .as_array() .unwrap_or_else(|| panic!("no signature help in {help:#?}")); assert_eq!(signatures.len(), 1); assert_eq!( signatures[0]["label"], "hint_sub (input logic clk, input logic [WIDTH-1:0] data, output logic ready)" ); assert_eq!(help["result"]["activeParameter"], 1, "`.data` is the second port"); let parameters = signatures[0]["parameters"].as_array().expect("parameters"); assert_eq!(parameters.len(), 3); let offsets = parameters[1]["label"].as_array().expect("label offsets"); let label = signatures[0]["label"].as_str().expect("label"); let (start, end) = (offsets[0].as_u64().expect("start") as usize, offsets[1].as_u64().expect("end") as usize); assert_eq!(&label[start..end], "input logic [WIDTH-1:0] data"); let _ = std::fs::remove_dir_all(&dir); } /// The same completion asked for by a client that never said it understands /// snippets โ€” the fallback the README promises. #[test] fn a_client_without_snippet_support_gets_the_skeleton_as_plain_text() { let dir = temp_dir("hintplain"); std::fs::write(dir.join("hint_sub.sv"), HINT_SUB).expect("write"); let top = dir.join("hint_top.sv"); std::fs::write(&top, HINT_TOP).expect("write"); let root = format!("file://{}", dir.display()); let top_uri = format!("file://{}", top.display()); let session = [ frame(&format!( r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"# )), frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), frame(&format!( r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{top_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, serde_json::to_string(HINT_TOP).expect("json") )), frame(&format!( r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/completion","params":{{"textDocument":{{"uri":"{top_uri}"}},"position":{{"line":2,"character":8}}}}}}"# )), frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), ] .concat(); let messages = talk(&session); let completion = messages.iter().find(|m| m["id"] == 2).expect("completion response"); let items = completion["result"]["items"].as_array().expect("a completion list"); let item = items .iter() .find(|item| item["label"] == "hint_sub") .unwrap_or_else(|| panic!("no module item in {items:#?}")); assert_eq!(item["insertTextFormat"], 1, "InsertTextFormat.PlainText"); let new_text = item["textEdit"]["newText"].as_str().expect("newText"); assert!(!new_text.contains('$'), "no tabstop syntax may reach this client: {new_text}"); assert!(new_text.contains(".data(data)"), "{new_text}"); let _ = std::fs::remove_dir_all(&dir); } /// Ghost text over the wire: the capability, the two triggers, and the shape /// of the item โ€” which is the whole contract, because a `lsp-types` bump that /// changed `InlineCompletionItem` would turn a working snippet into a literal /// `${1:cond}` in the user's buffer. #[test] fn inline_templates_round_trip_over_the_wire() { let dir = temp_dir("inline"); // Line 1 ends in a `begin` with no `end`; line 2 is an `if (` with nothing // after it, inside the block that begin opened. Line 6 is an `always @(`, // the one trigger that answers with more than one item. let top = "module top;\n always_comb begin\n if (\nendmodule\n\nmodule two;\n always @(\nendmodule\n"; let path = dir.join("top.sv"); std::fs::write(&path, top).expect("write"); let root = format!("file://{}", dir.display()); let uri = format!("file://{}", path.display()); let ask = |id: u32, line: u32, character: u32| { frame(&format!( r#"{{"jsonrpc":"2.0","id":{id},"method":"textDocument/inlineCompletion","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":{line},"character":{character}}},"context":{{"triggerKind":2}}}}}}"# )) }; let session = [ frame(&format!( r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{"textDocument":{{"inlineCompletion":{{"dynamicRegistration":true}}}}}}}}}}"# )), frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), frame(&format!( r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, serde_json::to_string(top).expect("json") )), // Just after the `begin` on line 1, and just after the `(` on line 2. ask(2, 1, 19), ask(3, 2, 8), // ...just after the `@(` on line 6, which answers with two items... ask(5, 6, 11), // ...and in the middle of the `always_comb` keyword, where there is // nothing to offer at all. ask(4, 1, 8), frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), ] .concat(); let messages = talk(&session); let capabilities = &messages.iter().find(|m| m["id"] == 1).expect("initialize response") ["result"]["capabilities"]; assert_eq!(capabilities["inlineCompletionProvider"], serde_json::json!(true)); let items = |id: u32| { let response = messages.iter().find(|m| m["id"] == id).expect("a response"); response["result"].clone() }; // The `begin` trigger: a newline, a tabstop one step in, and the `end` // back at the trigger line's own level. The indentation is **relative** โ€” // one `\t` per step and no trace of the site โ€” because the editor prepends // the insertion line's own leading whitespace to every line after the // first and re-spells the result in its own tabs-or-spaces. Sending the // absolute layout, as 0.6.0 did, indented the whole body twice and left // the `end` deeper than its `begin`. assert_eq!( items(2), serde_json::json!({ "items": [{ "insertText": { "kind": "snippet", "value": "\n\t$0\nend" }, "range": { "start": { "line": 1, "character": 19 }, "end": { "line": 1, "character": 19 } } }] }), "the exact wire shape the client turns into a SnippetString" ); // The `if (` trigger, from inside the same block. let item = &items(3)["items"][0]; assert_eq!(item["insertText"]["kind"], "snippet"); assert_eq!(item["insertText"]["value"], "${1:cond}) begin\n\t$0\nend"); assert_eq!(item["range"]["start"], item["range"]["end"], "an insertion, not a replacement"); // `always @(` is the one trigger with a list: the clocked block first, the // combinational one second, both at the same empty range. let two = items(5); let two = two["items"].as_array().expect("a list"); assert_eq!(two.len(), 2, "{two:#?}"); assert_eq!(two[0]["insertText"]["value"], "posedge ${1:clk}) begin\n\t$0\nend"); assert_eq!(two[1]["insertText"]["value"], "*) begin\n\t$0\nend"); assert_eq!(two[0]["range"], two[1]["range"], "both insert at the cursor"); assert_eq!(items(4), serde_json::Value::Null, "nowhere near a trigger"); let _ = std::fs::remove_dir_all(&dir); } /// `lucisv.inlineTemplates` really suppresses the request handler when pushed /// over the wire โ€” the link a unit test cannot check, since /// `inline.rs`'s own tests call `Workspace::set_client_settings` directly /// rather than going through `workspace/didChangeConfiguration`. #[test] fn the_inline_templates_setting_is_honoured_over_the_wire() { let dir = temp_dir("inline_setting"); let top = "module top;\n always_comb begin\nendmodule\n"; let path = dir.join("top.sv"); std::fs::write(&path, top).expect("write"); let root = format!("file://{}", dir.display()); let uri = format!("file://{}", path.display()); let ask = |id: u32| { frame(&format!( r#"{{"jsonrpc":"2.0","id":{id},"method":"textDocument/inlineCompletion","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":1,"character":19}},"context":{{"triggerKind":2}}}}}}"# )) }; let push = |setting: &str| { frame(&format!( r#"{{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{{"settings":{{"lucisv":{{"inlineTemplates":{setting}}}}}}}}}"# )) }; let session = [ frame(&format!( r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"# )), frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), frame(&format!( r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, serde_json::to_string(top).expect("json") )), // No push yet: the VS Code default is on. ask(2), push("false"), ask(3), // Mid-session, no restart, flips back on. push("true"), ask(4), frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), ] .concat(); let messages = talk(&session); let items = |id: u32| { let response = messages.iter().find(|m| m["id"] == id).expect("a response"); response["result"].clone() }; assert_ne!(items(2), serde_json::Value::Null, "on by default, nothing pushed yet"); assert_eq!(items(3), serde_json::Value::Null, "inlineTemplates: false suppresses it"); assert_ne!(items(4), serde_json::Value::Null, "inlineTemplates: true turns it back on"); let _ = std::fs::remove_dir_all(&dir); } /// The general tiers over the wire: keywords, project words and the two /// places a completion list must not appear. #[test] fn keyword_and_project_completion_round_trip_over_the_wire() { let dir = temp_dir("general"); std::fs::write(dir.join("other.sv"), "module other;\n logic widget_elsewhere;\nendmodule\n") .expect("write"); std::fs::write(dir.join("defs.svh"), "`define WIDGET_MACRO 1\n").expect("write"); // Line 2 holds the half-typed word, line 3 the same letters in a comment. let top = "module top;\n logic widget_local;\n assign x = widget\n // widget\nendmodule\n"; let path = dir.join("top.sv"); std::fs::write(&path, top).expect("write"); let root = format!("file://{}", dir.display()); let uri = format!("file://{}", path.display()); let session = [ frame(&format!( r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"# )), frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), frame(&format!( r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, serde_json::to_string(top).expect("json") )), // End of `widget` on line 2, mid-expression: no skeleton, everything else. frame(&format!( r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/completion","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":2,"character":19}}}}}}"# )), // End of `// widget` on line 3: inside a comment, so nothing at all. frame(&format!( r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/completion","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":3,"character":11}}}}}}"# )), frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), ] .concat(); let messages = talk(&session); let completion = messages.iter().find(|m| m["id"] == 2).expect("completion response"); let items = completion["result"]["items"] .as_array() .unwrap_or_else(|| panic!("no completion list in {completion:#?}")); let labelled = |label: &str| items.iter().find(|item| item["label"] == label).cloned(); let local = labelled("widget_local").expect("the declaration in scope"); assert_eq!(local["kind"], 6, "CompletionItemKind.Variable"); assert!(local["sortText"].as_str().expect("sortText").starts_with('1'), "{local:#?}"); let macro_name = labelled("WIDGET_MACRO").expect("a `define name"); assert!(macro_name["sortText"].as_str().expect("sortText").starts_with('2')); let elsewhere = labelled("widget_elsewhere").expect("a word used in the project"); assert_eq!(elsewhere["kind"], 1, "CompletionItemKind.Text"); // `5`, not `4`: M6 inserted the template tier above the keywords, which // pushed the keyword and word tiers' digits down by one. assert!(elsewhere["sortText"].as_str().expect("sortText").starts_with('5')); assert!( !items.iter().any(|item| item["sortText"].as_str().is_some_and(|s| s.starts_with('0'))), "mid-expression is no place for an instantiation skeleton: {items:#?}" ); // Inside the comment, the server declines outright. let in_comment = messages.iter().find(|m| m["id"] == 3).expect("completion response"); assert!(in_comment["result"].is_null(), "{in_comment:#?}"); let _ = std::fs::remove_dir_all(&dir); } /// The template tier over the wire, accept-shaped: what the client is handed /// for `if` inside an `always_comb`, and what a `.v` buffer gets instead. #[test] fn a_template_completion_round_trips_over_the_wire() { let dir = temp_dir("templates"); let top = "module top;\n always_comb begin\n if\n end\nendmodule\n"; let path = dir.join("top.sv"); std::fs::write(&path, top).expect("write"); let verilog = "module older;\n al\nendmodule\n"; let verilog_path = dir.join("older.v"); std::fs::write(&verilog_path, verilog).expect("write"); let root = format!("file://{}", dir.display()); let uri = format!("file://{}", path.display()); let verilog_uri = format!("file://{}", verilog_path.display()); let session = [ frame(&format!( r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{"textDocument":{{"completion":{{"completionItem":{{"snippetSupport":true}}}}}}}}}}}}"# )), frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), frame(&format!( r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, serde_json::to_string(top).expect("json") )), frame(&format!( r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{verilog_uri}","languageId":"verilog","version":1,"text":{}}}}}}}"#, serde_json::to_string(verilog).expect("json") )), // End of `if` on line 2 of the SystemVerilog buffer. frame(&format!( r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/completion","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":2,"character":6}}}}}}"# )), // End of `al` on line 1 of the Verilog one, at module-item position. frame(&format!( r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/completion","params":{{"textDocument":{{"uri":"{verilog_uri}"}},"position":{{"line":1,"character":4}}}}}}"# )), frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), ] .concat(); let messages = talk(&session); let completion = messages.iter().find(|m| m["id"] == 2).expect("completion response"); let items = completion["result"]["items"] .as_array() .unwrap_or_else(|| panic!("no completion list in {completion:#?}")); let labelled = |items: &[serde_json::Value], label: &str| { items.iter().find(|item| item["label"] == label).cloned() }; let template = labelled(items, "if begin/end").expect("the if template"); assert_eq!(template["kind"], 15, "CompletionItemKind.Snippet"); assert_eq!(template["insertTextFormat"], 2, "InsertTextFormat.Snippet"); assert_eq!(template["filterText"], "if"); assert_eq!( template["textEdit"]["newText"], "if (${1:cond}) begin\n $0\n end", "{template:#?}" ); // The body is laid out at the site's own indentation, so the client must // be told not to indent it a second time: VS Code's suggest controller // passes `adjustWhitespace: true` unless the item carries `asIs`, and its // snippet session then prepends the insertion line's leading whitespace to // every line after the first. `1` is `InsertTextMode.asIs`. assert_eq!(template["insertTextMode"], 1, "InsertTextMode.asIs: {template:#?}"); // The replaced range is exactly the two letters typed. assert_eq!(template["textEdit"]["range"]["start"]["line"], 2); assert_eq!(template["textEdit"]["range"]["start"]["character"], 4); assert_eq!(template["textEdit"]["range"]["end"]["character"], 6); assert!(template["sortText"].as_str().expect("sortText").starts_with('3')); // The keyword survives beside it, one tier down. let keyword = labelled(items, "if").expect("the keyword"); assert_eq!(keyword["kind"], 14, "CompletionItemKind.Keyword"); assert!(keyword["sortText"].as_str().expect("sortText").starts_with('4')); // A `.v` buffer is offered Verilog's `always`, never `always_ff`. let verilog = messages.iter().find(|m| m["id"] == 3).expect("completion response"); let items = verilog["result"]["items"].as_array().expect("a completion list"); assert!(labelled(items, "always @(posedge clk)").is_some(), "{items:#?}"); assert!( labelled(items, "always_ff @(posedge clk)").is_none(), "a .v file has no always_ff: {items:#?}" ); let _ = std::fs::remove_dir_all(&dir); } /// The three navigation capabilities of round M7, over the wire in one /// session: a reference set that spans two files, the folds of a buffer, and /// the occurrences of a signal inside it. const NAV_SUB: &str = "module sub (input logic clk);\nendmodule\n"; const NAV_TOP: &str = concat!( "module top;\n", // 0 " logic clk;\n", // 1 " sub u_a (.clk(clk));\n", // 2 " assign clk = 1'b0;\n", // 3 "endmodule\n", // 4 ); #[test] fn cross_file_references_folding_and_highlights_round_trip_over_the_wire() { let dir = temp_dir("nav"); let sub = dir.join("sub.sv"); std::fs::write(&sub, NAV_SUB).expect("write"); let top = dir.join("top.sv"); std::fs::write(&top, NAV_TOP).expect("write"); let root = format!("file://{}", dir.display()); let uri = format!("file://{}", top.display()); let sub_uri = format!("file://{}", sub.display()); let session = [ frame(&format!( r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"# )), frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), frame(&format!( r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, serde_json::to_string(NAV_TOP).expect("json") )), // The `sub` of the instantiation on line 2: its declaration lives in // the other file, and only a cross-file answer can say so. frame(&format!( r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/references","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":2,"character":2}},"context":{{"includeDeclaration":true}}}}}}"# )), frame(&format!( r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/references","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":2,"character":2}},"context":{{"includeDeclaration":false}}}}}}"# )), frame(&format!( r#"{{"jsonrpc":"2.0","id":4,"method":"textDocument/foldingRange","params":{{"textDocument":{{"uri":"{uri}"}}}}}}"# )), // The `clk` declared on line 1 โ€” a plain local signal, so the answer // is this file's occurrences of it and nothing else. frame(&format!( r#"{{"jsonrpc":"2.0","id":5,"method":"textDocument/documentHighlight","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":1,"character":8}}}}}}"# )), frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), ] .concat(); let messages = talk(&session); let initialize = messages.iter().find(|m| m["id"] == 1).expect("initialize response"); let capabilities = &initialize["result"]["capabilities"]; assert_eq!(capabilities["referencesProvider"], serde_json::json!(true)); assert_eq!(capabilities["foldingRangeProvider"], serde_json::json!(true)); assert_eq!(capabilities["documentHighlightProvider"], serde_json::json!(true)); let response = |id: u32| -> &serde_json::Value { messages.iter().find(|m| m["id"] == id).unwrap_or_else(|| panic!("no {id}: {messages:#?}")) }; let places = |id: u32| -> Vec<(String, u64, u64)> { response(id)["result"] .as_array() .unwrap_or_else(|| panic!("response {id} is not a list: {:#?}", response(id))) .iter() .map(|l| { ( l["uri"].as_str().expect("uri").to_string(), l["range"]["start"]["line"].as_u64().expect("line"), l["range"]["start"]["character"].as_u64().expect("character"), ) }) .collect() }; assert_eq!( places(2), vec![(sub_uri.clone(), 0, 7), (uri.clone(), 2, 2)], "the module declaration in sub.sv, and the instantiation here" ); assert_eq!(places(3), vec![(uri.clone(), 2, 2)], "without the declaration"); let folds = response(4)["result"].as_array().expect("a folding list"); assert_eq!(folds.len(), 1, "the module, and nothing that never closed: {folds:#?}"); assert_eq!(folds[0]["startLine"], 0); assert_eq!(folds[0]["endLine"], 3, "one short of `endmodule`, which stays visible"); assert_eq!(folds[0]["kind"], "region"); let highlights = response(5)["result"].as_array().expect("a highlight list"); let at: Vec<(u64, u64)> = highlights .iter() .map(|h| { ( h["range"]["start"]["line"].as_u64().expect("line"), h["range"]["start"]["character"].as_u64().expect("character"), ) }) .collect(); assert_eq!( at, vec![(1, 8), (2, 16), (3, 9)], "the declaration, the connected expression and the assignment โ€” not the `.clk` port name" ); assert!(highlights.iter().all(|h| h["kind"] == 1), "DocumentHighlightKind.Text"); let _ = std::fs::remove_dir_all(&dir); } const INLAY_SUB: &str = "\ module inlay_sub #( parameter int WIDTH = 8, parameter int DEPTH = 16 ) ( input logic clk, input logic rst_n, input logic [WIDTH-1:0] data ); endmodule "; /// Line 1 is ordered โ€” three ghost labels and two on the overrides. Line 2 is /// named, so it gets none. Line 3 instantiates a module nothing declares. const INLAY_TOP: &str = "\ module inlay_top; inlay_sub #(4, 8) u1 (clk, rst_n, data); inlay_sub u2 (.clk(clk), .rst_n(rst_n), .data(data)); nope u3 (a, b, c); endmodule "; #[test] fn inlay_hints_round_trip_over_the_wire() { // What only an e2e test can check: that the capability is advertised in // the shape a client reads, and that a range-scoped request comes back // with the exact labels at the exact positions the editor draws at. let dir = temp_dir("inlay"); std::fs::write(dir.join("inlay_sub.sv"), INLAY_SUB).expect("write"); let top = dir.join("inlay_top.sv"); std::fs::write(&top, INLAY_TOP).expect("write"); let root = format!("file://{}", dir.display()); let uri = format!("file://{}", top.display()); let session = [ frame(&format!( r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"# )), frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), frame(&format!( r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, serde_json::to_string(INLAY_TOP).expect("json") )), // The whole file. frame(&format!( r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/inlayHint","params":{{"textDocument":{{"uri":"{uri}"}},"range":{{"start":{{"line":0,"character":0}},"end":{{"line":4,"character":0}}}}}}}}"# )), // Only the named line, which has nothing to hint. frame(&format!( r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/inlayHint","params":{{"textDocument":{{"uri":"{uri}"}},"range":{{"start":{{"line":2,"character":0}},"end":{{"line":2,"character":60}}}}}}}}"# )), frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), ] .concat(); let messages = talk(&session); let initialize = messages.iter().find(|m| m["id"] == 1).expect("initialize response"); let provider = &initialize["result"]["capabilities"]["inlayHintProvider"]; assert!(provider.is_object(), "options, not a bare `true`: {provider:#?}"); assert!(provider.get("resolveProvider").is_none(), "every hint is complete: {provider:#?}"); let response = |id: u32| -> &serde_json::Value { messages.iter().find(|m| m["id"] == id).unwrap_or_else(|| panic!("no {id}: {messages:#?}")) }; let hints: Vec<(u64, u64, String, u64, bool)> = response(2)["result"] .as_array() .expect("a hint list") .iter() .map(|h| { ( h["position"]["line"].as_u64().expect("line"), h["position"]["character"].as_u64().expect("character"), h["label"].as_str().expect("a string label").to_string(), h["kind"].as_u64().expect("kind"), h["paddingRight"].as_bool().expect("paddingRight"), ) }) .collect(); // ` inlay_sub #(4, 8) u1 (clk, rst_n, data);` // column 14 is the `4`, 17 the `8`, 24 `clk`, 29 `rst_n`, 36 `data`. assert_eq!( hints, vec![ (1, 14, "WIDTH:".to_string(), 2, true), (1, 17, "DEPTH:".to_string(), 2, true), (1, 24, "clk:".to_string(), 2, true), (1, 29, "rst_n:".to_string(), 2, true), (1, 36, "data:".to_string(), 2, true), ], "the ordered line only โ€” the named one and the unknown module say nothing" ); assert_eq!( response(3)["result"].as_array().expect("a hint list").len(), 0, "a named connection list has nothing to add" ); let _ = std::fs::remove_dir_all(&dir); } /// A live session: unlike `talk`, one message goes out at a time and the /// answers are read as they arrive. /// /// That is what lets a test change the *disk* mid-session and know the server /// has not looked yet โ€” `talk` writes the whole script up front, so anything /// it does to the filesystem afterwards races the server. struct Live { child: std::process::Child, stdin: std::process::ChildStdin, stdout: BufReader, } impl Live { fn start() -> Live { let mut child = Command::new(env!("CARGO_BIN_EXE_lucisv-server")) .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::null()) .spawn() .expect("the server binary starts"); let stdin = child.stdin.take().expect("stdin"); let stdout = BufReader::new(child.stdout.take().expect("stdout")); Live { child, stdin, stdout } } fn send(&mut self, payload: &str) { self.stdin.write_all(frame(payload).as_bytes()).expect("write"); self.stdin.flush().expect("flush"); } /// Read until a message the predicate accepts, and return it. /// /// Capped rather than unbounded: a test that hangs forever waiting for a /// message the server will never send is far worse to debug than one that /// fails with the transcript. fn wait_for(&mut self, wanted: impl Fn(&serde_json::Value) -> bool) -> serde_json::Value { let mut seen = Vec::new(); for _ in 0..500 { let Some(message) = read_message(&mut self.stdout) else { break }; if wanted(&message) { return message; } seen.push(message); } panic!("the server never said what was waited for; it said {seen:#?}"); } fn finish(mut self) { self.send(r#"{"jsonrpc":"2.0","id":99,"method":"shutdown","params":null}"#); self.wait_for(|m| m["id"] == 99); self.send(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#); drop(self.stdin); let status = self.child.wait().expect("the server exits"); assert!(status.success(), "clean exit, got {status:?}"); } } #[test] fn a_file_created_mid_session_is_indexed_through_a_watched_files_notification() { // The whole feature, end to end and over the wire: a client that says it // can watch files is *asked* to, a file appears on disk that no editor // ever opened or saved, one notification says so, and the very next // `workspace/symbol` finds what is inside it. let dir = temp_dir("watchedfiles"); let open = dir.join("top.sv"); std::fs::write(&open, "package top_pkg;\n localparam K = 1;\nendpackage\n").expect("write"); let root = format!("file://{}", dir.display()); let open_uri = format!("file://{}", open.display()); let pulled = dir.join("pulled.sv"); let pulled_uri = format!("file://{}", pulled.display()); let query = |id: u32, name: &str| { format!( r#"{{"jsonrpc":"2.0","id":{id},"method":"workspace/symbol","params":{{"query":"{name}"}}}}"# ) }; let mut live = Live::start(); live.send(&format!( r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{"workspace":{{"didChangeWatchedFiles":{{"dynamicRegistration":true}}}}}}}}}}"# )); live.wait_for(|m| m["id"] == 1); live.send(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#); // The registration itself: without it a real client watches nothing, and // every assertion below would be about a notification no editor sends. let registration = live.wait_for(|m| m["method"] == "client/registerCapability"); let registered = ®istration["params"]["registrations"][0]; assert_eq!(registered["method"], "workspace/didChangeWatchedFiles", "{registration:#?}"); assert_eq!( registered["registerOptions"]["watchers"], serde_json::json!([{ "globPattern": "**/*.{v,vh,sv,svh}" }]), "{registration:#?}" ); // Answer it the way a real client does. Nothing depends on the answer; // this proves the server tolerates one arriving mid-session. let id = serde_json::to_string(®istration["id"]).expect("json"); live.send(&format!(r#"{{"jsonrpc":"2.0","id":{id},"result":null}}"#)); // An open buffer, so the republish half of the rebuild has somewhere to // land โ€” and so the "no save anywhere" claim has a buffer to not save. live.send(&format!( r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{open_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, serde_json::to_string("package top_pkg;\n localparam K = 1;\nendpackage\n") .expect("json") )); live.send(&query(2, "pulled_pkg")); let before = live.wait_for(|m| m["id"] == 2); assert_eq!(before["result"].as_array().map(|a| a.len()), Some(0), "premise: not on disk yet"); // The `git pull`: a file appears, and nothing in the editor knows. std::fs::write(&pulled, "package pulled_pkg;\n localparam K = 1;\nendpackage\n") .expect("write"); live.send(&format!( r#"{{"jsonrpc":"2.0","method":"workspace/didChangeWatchedFiles","params":{{"changes":[{{"uri":"{pulled_uri}","type":1}}]}}}}"# )); live.send(&query(3, "pulled_pkg")); let after = live.wait_for(|m| m["id"] == 3); let hits = after["result"].as_array().expect("a symbol list"); assert_eq!(hits.len(), 1, "the created file is in the index: {after:#?}"); assert_eq!(hits[0]["location"]["uri"], pulled_uri.as_str(), "{after:#?}"); // ... and the deletion half, on the same path. std::fs::remove_file(&pulled).expect("remove"); live.send(&format!( r#"{{"jsonrpc":"2.0","method":"workspace/didChangeWatchedFiles","params":{{"changes":[{{"uri":"{pulled_uri}","type":3}}]}}}}"# )); live.send(&query(4, "pulled_pkg")); let gone = live.wait_for(|m| m["id"] == 4); assert_eq!(gone["result"].as_array().map(|a| a.len()), Some(0), "{gone:#?}"); live.finish(); let _ = std::fs::remove_dir_all(&dir); } #[test] fn a_client_that_cannot_watch_files_is_never_asked_to() { // The other half of the guard: every existing client โ€” `smoke.js` and // every other session in this file โ€” sends `capabilities: {}`, and must // still see nothing but answers to what it asked. let dir = temp_dir("nowatch"); std::fs::write(dir.join("m.sv"), UNFORMATTED).expect("write"); let root = format!("file://{}", dir.display()); let session = [ frame(&format!( r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"# )), frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), ] .concat(); let messages = talk(&session); assert!( !messages.iter().any(|m| m["method"] == "client/registerCapability"), "a client that did not advertise dynamic registration must not be asked: {messages:#?}" ); let _ = std::fs::remove_dir_all(&dir); } /// A project whose filelist carries a `+incdir+`: `top.sv` includes a header /// that only that incdir can find, and two files in the index define the same /// macro โ€” one reachable through the include, one not. const INCLUDE_TOP: &str = "\ `include \"defs.svh\" module include_top; wire [`WIDTH-1:0] a; endmodule "; #[test] fn include_links_definition_and_a_reachable_define_round_trip_over_the_wire() { // What only an e2e test can check: that `documentLinkProvider` is // advertised in the shape a client reads, that the `+incdir+` from a // `lucisv.toml`-configured filelist survives the whole trip from disk to a // resolved URI, and that the two capabilities answer the same line. let dir = temp_dir("include"); std::fs::create_dir_all(dir.join("inc")).expect("inc"); std::fs::create_dir_all(dir.join("other")).expect("other"); std::fs::create_dir_all(dir.join("rtl")).expect("rtl"); let defs = dir.join("inc/defs.svh"); std::fs::write(&defs, "`define WIDTH 8\n").expect("write"); std::fs::write(dir.join("other/elsewhere.svh"), "`define WIDTH 16\n").expect("write"); let top = dir.join("rtl/top.sv"); std::fs::write(&top, INCLUDE_TOP).expect("write"); std::fs::write( dir.join("files.f"), "+incdir+inc\nrtl/top.sv\ninc/defs.svh\nother/elsewhere.svh\n", ) .expect("write"); std::fs::write(dir.join("lucisv.toml"), "filelist = \"files.f\"\n").expect("write"); let root = format!("file://{}", dir.display()); let uri = format!("file://{}", top.display()); let defs_uri = format!("file://{}", defs.display()); let session = [ frame(&format!( r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"# )), frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), frame(&format!( r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, serde_json::to_string(INCLUDE_TOP).expect("json") )), frame(&format!( r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/documentLink","params":{{"textDocument":{{"uri":"{uri}"}}}}}}"# )), // The cursor in the middle of the quoted path on line 0. frame(&format!( r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/definition","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":0,"character":12}}}}}}"# )), // `` `WIDTH `` on line 2: two files define it, one of them included. frame(&format!( r#"{{"jsonrpc":"2.0","id":4,"method":"textDocument/hover","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":2,"character":9}}}}}}"# )), frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), ] .concat(); let messages = talk(&session); let response = |id: u32| -> &serde_json::Value { messages.iter().find(|m| m["id"] == id).unwrap_or_else(|| panic!("no {id}: {messages:#?}")) }; let capabilities = &response(1)["result"]["capabilities"]; assert_eq!(capabilities["documentLinkProvider"]["resolveProvider"], serde_json::json!(false)); let links = response(2)["result"].as_array().expect("a link list"); assert_eq!(links.len(), 1, "one resolvable include: {links:#?}"); assert_eq!(links[0]["target"], defs_uri.as_str(), "found through `+incdir+inc`"); assert_eq!(links[0]["range"]["start"], serde_json::json!({"line": 0, "character": 9})); assert_eq!(links[0]["range"]["end"], serde_json::json!({"line": 0, "character": 19})); let locations = response(3)["result"].as_array().expect("a location list"); assert_eq!(locations.len(), 1, "{locations:#?}"); assert_eq!(locations[0]["uri"], defs_uri.as_str(), "the same file the link names"); assert_eq!(locations[0]["range"]["start"], serde_json::json!({"line": 0, "character": 0})); let hover = response(4)["result"]["contents"]["value"].as_str().expect("hover markdown"); assert!(hover.contains("`define WIDTH 8"), "the included definition: got {hover}"); assert!(!hover.contains("`define WIDTH 16"), "not the unreachable one: got {hover}"); assert!(hover.contains("defs.svh:1"), "named with its origin: got {hover}"); let _ = std::fs::remove_dir_all(&dir); } /// QA (M10 include-nav): the same round trip as /// `include_links_definition_and_a_reachable_define_round_trip_over_the_wire`, /// but with a space in the workspace directory name. `path_to_uri` /// percent-encodes a space (pinned in `includes.rs`'s /// `a_path_with_a_space_in_it_comes_back_percent_encoded`) but every e2e /// session in this file hand-rolls its `file://` URIs unencoded, because none /// of them has ever needed a space in a directory name โ€” so this is the first /// test that exercises the wire format's own percent-encoding requirement /// (`uri_to_path` decodes it, `rootUri`/`textDocument.uri` must supply it) for /// this feature specifically. #[test] fn include_nav_round_trips_in_a_workspace_whose_directory_has_a_space() { let dir = temp_dir("include spaced"); std::fs::create_dir_all(dir.join("inc")).expect("inc"); let defs = dir.join("inc/defs.svh"); std::fs::write(&defs, "`define WIDTH 8\n").expect("write"); let top = dir.join("top.sv"); std::fs::write(&top, INCLUDE_TOP).expect("write"); std::fs::write(dir.join("files.f"), "+incdir+inc\ntop.sv\ninc/defs.svh\n").expect("write"); std::fs::write(dir.join("lucisv.toml"), "filelist = \"files.f\"\n").expect("write"); // The URIs the wire actually needs: the directory's own space encoded, // matching what `path_to_uri` would produce and `uri_to_path` requires. let root = format!("file://{}", dir.display()).replace(' ', "%20"); let uri = format!("file://{}", top.display()).replace(' ', "%20"); let defs_uri = format!("file://{}", defs.display()).replace(' ', "%20"); let session = [ frame(&format!( r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"# )), frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), frame(&format!( r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, serde_json::to_string(INCLUDE_TOP).expect("json") )), frame(&format!( r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/documentLink","params":{{"textDocument":{{"uri":"{uri}"}}}}}}"# )), frame(&format!( r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/definition","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":0,"character":12}}}}}}"# )), frame(&format!( r#"{{"jsonrpc":"2.0","id":4,"method":"textDocument/hover","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":2,"character":9}}}}}}"# )), frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), ] .concat(); let messages = talk(&session); let response = |id: u32| -> &serde_json::Value { messages.iter().find(|m| m["id"] == id).unwrap_or_else(|| panic!("no {id}: {messages:#?}")) }; let links = response(2)["result"].as_array().expect("a link list"); assert_eq!(links.len(), 1, "{links:#?}"); assert_eq!(links[0]["target"], defs_uri.as_str(), "the space survived the round trip"); let locations = response(3)["result"].as_array().expect("a location list"); assert_eq!(locations.len(), 1, "{locations:#?}"); assert_eq!(locations[0]["uri"], defs_uri.as_str()); let hover = response(4)["result"]["contents"]["value"].as_str().expect("hover markdown"); assert!(hover.contains("`define WIDTH 8"), "got {hover}"); assert!(hover.contains("defs.svh:1"), "got {hover}"); let _ = std::fs::remove_dir_all(&dir); } /// QA round 2 (M10 include-nav, re-verifying the case-sensitivity fix): the /// real binary, over the real wire, on a case-mismatched include โ€” the thing /// a unit test calling `IncludeGraph::resolve` or `hover(...)` directly /// cannot fully settle, since it never proves what URI actually lands in the /// client's hands. `top.sv` writes `` `include "defs.svh"``, but the file on /// disk (and in the filelist) is `Defs.svh`. Both `documentLink`'s target and /// F12 (`textDocument/definition`) must carry the *index's* spelling /// (`Defs.svh`), not the as-written one โ€” otherwise an editor that diffs URIs /// against its own open-buffer list (most do, to decide whether a jump lands /// on an already-open tab) would treat the two spellings as different files. /// Case-gated: the premise is a case-insensitive default filesystem. #[cfg(any(target_os = "macos", target_os = "windows"))] #[test] fn go_to_definition_lands_on_the_indexs_own_spelling_not_the_includes() { let dir = temp_dir("casewire"); let defs = dir.join("Defs.svh"); std::fs::write(&defs, "`define WIDTH 8\n").expect("write"); let top = dir.join("top.sv"); let top_text = "`include \"defs.svh\"\nmodule top;\nendmodule\n"; std::fs::write(&top, top_text).expect("write"); let root = format!("file://{}", dir.display()); let uri = format!("file://{}", top.display()); // The URI the *index* would produce for the real file, capital D. let indexed_uri = format!("file://{}", defs.display()); assert_ne!(indexed_uri, indexed_uri.to_lowercase(), "premise: the fixture has a real capital"); let session = [ frame(&format!( r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"# )), frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), frame(&format!( r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, serde_json::to_string(top_text).expect("json") )), frame(&format!( r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/documentLink","params":{{"textDocument":{{"uri":"{uri}"}}}}}}"# )), frame(&format!( r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/definition","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":0,"character":12}}}}}}"# )), frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), ] .concat(); let messages = talk(&session); let response = |id: u32| -> &serde_json::Value { messages.iter().find(|m| m["id"] == id).unwrap_or_else(|| panic!("no {id}: {messages:#?}")) }; let links = response(2)["result"].as_array().expect("a link list"); assert_eq!(links.len(), 1, "{links:#?}"); assert_eq!( links[0]["target"], indexed_uri.as_str(), "documentLink must carry the index's own spelling, not `defs.svh` as written" ); let locations = response(3)["result"].as_array().expect("a location list"); assert_eq!(locations.len(), 1, "{locations:#?}"); assert_eq!( locations[0]["uri"], indexed_uri.as_str(), "F12 must land on the file the way the index spells it" ); let _ = std::fs::remove_dir_all(&dir); } const HIER_SUB: &str = "module hier_sub (input logic clk);\nendmodule\n"; const HIER_MID: &str = "\ module hier_mid; hier_sub u_a (.clk(1'b0)); hier_sub u_b (.clk(1'b1)); endmodule "; const HIER_TOP: &str = "module hier_top;\n hier_mid u_mid ();\nendmodule\n"; #[test] fn the_module_hierarchy_round_trips_over_the_wire_in_both_directions() { // What only an e2e test can check: that the capability is advertised in // the shape a client reads, and that an item the *client* sends back โ€” // rather than one this process still holds โ€” is what the two directions // are answered from. let dir = temp_dir("hierarchy"); let sub = dir.join("hier_sub.sv"); std::fs::write(&sub, HIER_SUB).expect("write"); let mid = dir.join("hier_mid.sv"); std::fs::write(&mid, HIER_MID).expect("write"); let top = dir.join("hier_top.sv"); std::fs::write(&top, HIER_TOP).expect("write"); let root = format!("file://{}", dir.display()); let uri = format!("file://{}", top.display()); let mid_uri = format!("file://{}", mid.display()); let sub_uri = format!("file://{}", sub.display()); // The item a client holds after `prepareCallHierarchy` and sends back for // each direction: `hier_mid`, declared on lines 0..3 of `hier_mid.sv`. let mid_item = format!( r#"{{"name":"hier_mid","kind":2,"uri":"{mid_uri}","range":{{"start":{{"line":0,"character":0}},"end":{{"line":3,"character":9}}}},"selectionRange":{{"start":{{"line":0,"character":7}},"end":{{"line":0,"character":15}}}}}}"# ); let session = [ frame(&format!( r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"# )), frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), frame(&format!( r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, serde_json::to_string(HIER_TOP).expect("json") )), // The cursor on the `hier_mid` of the instantiation on line 1. frame(&format!( r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/prepareCallHierarchy","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":1,"character":4}}}}}}"# )), frame(&format!( r#"{{"jsonrpc":"2.0","id":3,"method":"callHierarchy/incomingCalls","params":{{"item":{mid_item}}}}}"# )), frame(&format!( r#"{{"jsonrpc":"2.0","id":4,"method":"callHierarchy/outgoingCalls","params":{{"item":{mid_item}}}}}"# )), // The instance name is not a module, so there is no hierarchy to open. frame(&format!( r#"{{"jsonrpc":"2.0","id":5,"method":"textDocument/prepareCallHierarchy","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":1,"character":12}}}}}}"# )), frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), ] .concat(); let messages = talk(&session); let response = |id: u32| -> &serde_json::Value { messages.iter().find(|m| m["id"] == id).unwrap_or_else(|| panic!("no {id}: {messages:#?}")) }; let capabilities = &response(1)["result"]["capabilities"]; assert_eq!(capabilities["callHierarchyProvider"], serde_json::json!(true)); let prepared = response(2)["result"].as_array().expect("a list of items"); assert_eq!(prepared.len(), 1, "{prepared:#?}"); assert_eq!( prepared[0], serde_json::from_str::(&mid_item).expect("json"), "the item the client will send back is exactly the one built here" ); let incoming = response(3)["result"].as_array().expect("a list of calls"); assert_eq!(incoming.len(), 1, "one caller: {incoming:#?}"); assert_eq!(incoming[0]["from"]["name"], "hier_top"); assert_eq!(incoming[0]["from"]["uri"], uri.as_str()); assert_eq!(incoming[0]["from"]["kind"], 2, "SymbolKind.Module"); assert_eq!( incoming[0]["fromRanges"], serde_json::json!([{ "start": { "line": 1, "character": 2 }, "end": { "line": 1, "character": 10 } }]), "the instantiation site inside `hier_top`" ); let outgoing = response(4)["result"].as_array().expect("a list of calls"); assert_eq!(outgoing.len(), 1, "one distinct callee: {outgoing:#?}"); assert_eq!(outgoing[0]["to"]["name"], "hier_sub"); assert_eq!(outgoing[0]["to"]["uri"], sub_uri.as_str()); assert_eq!( outgoing[0]["fromRanges"], serde_json::json!([ { "start": { "line": 1, "character": 2 }, "end": { "line": 1, "character": 10 } }, { "start": { "line": 2, "character": 2 }, "end": { "line": 2, "character": 10 } }, ]), "both sites of the same module, in one call" ); assert_eq!(response(5)["result"], serde_json::Value::Null, "an instance name is no module"); let _ = std::fs::remove_dir_all(&dir); } // QA (2026-08-25): an independent stdio round trip covering an `incomingCalls` // answer that carries *two* `fromRanges` in one call, rather than reusing the // dev's own e2e fixture (whose `incomingCalls` case is single-range; only its // `outgoingCalls` case has two). `sub2` is instantiated twice inside `mid2`. #[test] fn qa_incoming_calls_with_two_fromranges_round_trips_over_the_wire() { let dir = temp_dir("qa_hierarchy_incoming_two_ranges"); let sub = dir.join("sub2.sv"); std::fs::write(&sub, "module sub2 (input logic clk);\nendmodule\n").expect("write"); let mid = dir.join("mid2.sv"); let mid_text = "\ module mid2; sub2 u_a (.clk(1'b0)); sub2 u_b (.clk(1'b1)); endmodule "; std::fs::write(&mid, mid_text).expect("write"); let root = format!("file://{}", dir.display()); let mid_uri = format!("file://{}", mid.display()); let session = [ frame(&format!( r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"# )), frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), frame(&format!( r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{mid_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, serde_json::to_string(mid_text).expect("json") )), // Cursor on `sub2` of the first instantiation. frame(&format!( r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/prepareCallHierarchy","params":{{"textDocument":{{"uri":"{mid_uri}"}},"position":{{"line":1,"character":4}}}}}}"# )), frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), ] .concat(); let messages = talk(&session); let response = |id: u32| -> &serde_json::Value { messages.iter().find(|m| m["id"] == id).unwrap_or_else(|| panic!("no {id}: {messages:#?}")) }; let prepared = response(2)["result"].as_array().expect("a list of items"); assert_eq!(prepared.len(), 1, "{prepared:#?}"); let sub2_item = prepared[0].clone(); // A second round trip, so the incoming request is answered fresh against // the item the first session handed back โ€” exactly what a real client // does across two separate requests. let session2 = [ frame(&format!( r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"# )), frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), frame(&format!( r#"{{"jsonrpc":"2.0","id":3,"method":"callHierarchy/incomingCalls","params":{{"item":{}}}}}"#, serde_json::to_string(&sub2_item).expect("json") )), frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), ] .concat(); let messages2 = talk(&session2); let response2 = |id: u32| -> &serde_json::Value { messages2 .iter() .find(|m| m["id"] == id) .unwrap_or_else(|| panic!("no {id}: {messages2:#?}")) }; let incoming = response2(3)["result"].as_array().expect("a list of calls"); assert_eq!(incoming.len(), 1, "one caller: {incoming:#?}"); assert_eq!(incoming[0]["from"]["name"], "mid2"); let from_ranges = incoming[0]["fromRanges"].as_array().expect("fromRanges"); assert_eq!(from_ranges.len(), 2, "two instantiation sites in one call: {from_ranges:#?}"); assert_eq!(from_ranges[0]["start"]["line"], 1); assert_eq!(from_ranges[1]["start"]["line"], 2); let _ = std::fs::remove_dir_all(&dir); } /// M14 (macro-expansion): a macro call hovered over the real wire, whose /// definition lives in an included file. The exact markdown a client receives /// is what this pins โ€” a unit test can prove the string is built, only a round /// trip proves it survives serialization into `contents.value`. #[test] fn a_macro_call_hover_carries_its_single_step_expansion_over_the_wire() { let dir = temp_dir("expand"); std::fs::write(dir.join("defs.svh"), "`define MAX(a, b) ((a) > (b) ? (a) : (b))\n") .expect("write"); let top = dir.join("top.sv"); let top_text = "\ `include \"defs.svh\" module top; wire [7:0] w = `MAX(p, q + 1); endmodule "; std::fs::write(&top, top_text).expect("write"); let root = format!("file://{}", dir.display()); let uri = format!("file://{}", top.display()); let session = [ frame(&format!( r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"# )), frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), frame(&format!( r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, serde_json::to_string(top_text).expect("json") )), // The cursor inside `` `MAX`` on line 2. frame(&format!( r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/hover","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":2,"character":20}}}}}}"# )), frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), ] .concat(); let messages = talk(&session); let response = messages .iter() .find(|m| m["id"] == 2) .unwrap_or_else(|| panic!("no hover response: {messages:#?}")); let hover = response["result"]["contents"]["value"].as_str().expect("hover markdown"); assert_eq!( hover, "defined in `defs.svh:1`\n\n\ ```systemverilog\n`define MAX(a, b) ((a) > (b) ? (a) : (b))\n```\n\n\ **expands to**\n\n\ ```systemverilog\n((p) > (q + 1) ? (p) : (q + 1))\n```", "the whole card, byte for byte" ); let _ = std::fs::remove_dir_all(&dir); } /// A buffer with one parse error and one lint finding, for the diagnostics /// sessions below. const DIAGNOSTIC_SOURCE: &str = "module m;\n\twire ;\nendmodule\n"; #[test] fn a_pulling_client_is_answered_and_never_pushed_over_the_wire() { // What only an e2e test can check: that a client which advertised // `textDocument.diagnostic` at `initialize` really is pushed nothing โ€” // the "never both models" rule is about the wire, not about a handler. let dir = temp_dir("pull"); let file = dir.join("m.sv"); std::fs::write(&file, DIAGNOSTIC_SOURCE).expect("write"); let root = format!("file://{}", dir.display()); let uri = format!("file://{}", file.display()); let mut live = Live::start(); live.send(&format!( r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{"textDocument":{{"diagnostic":{{}}}}}}}}}}"# )); let initialize = live.wait_for(|m| m["id"] == 1); let provider = &initialize["result"]["capabilities"]["diagnosticProvider"]; assert_eq!(provider["identifier"], "lucisv", "{initialize:#?}"); assert_eq!(provider["interFileDependencies"], true, "{initialize:#?}"); assert_eq!(provider["workspaceDiagnostics"], true, "{initialize:#?}"); live.send(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#); live.send(&format!( r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, serde_json::to_string(DIAGNOSTIC_SOURCE).expect("json") )); live.send(&format!( r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/diagnostic","params":{{"textDocument":{{"uri":"{uri}"}},"identifier":"lucisv"}}}}"# )); // The next thing the server says is either the answer or a push it must // never have sent โ€” so this one wait proves both halves. let full = live.wait_for(|m| m["id"] == 2 || m["method"] == "textDocument/publishDiagnostics"); assert_eq!(full["id"], 2, "a pulling client must not be pushed diagnostics: {full:#?}"); assert_eq!(full["result"]["kind"], "full"); let items = full["result"]["items"].as_array().expect("items"); assert_eq!(items.len(), 2, "the parse error and the lint warning: {full:#?}"); assert!(items.iter().all(|item| item["source"] == "lucisv"), "{items:#?}"); let result_id = full["result"]["resultId"].as_str().expect("a result id").to_string(); // Nothing moved, so the client's cached report still stands. live.send(&format!( r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/diagnostic","params":{{"textDocument":{{"uri":"{uri}"}},"identifier":"lucisv","previousResultId":"{result_id}"}}}}"# )); let unchanged = live.wait_for(|m| m["id"] == 3); assert_eq!(unchanged["result"]["kind"], "unchanged", "{unchanged:#?}"); // An edit moves it, and the fixed buffer comes back clean. live.send(&format!( r#"{{"jsonrpc":"2.0","method":"textDocument/didChange","params":{{"textDocument":{{"uri":"{uri}","version":2}},"contentChanges":[{{"text":{}}}]}}}}"#, serde_json::to_string("module m;\n wire a;\nendmodule\n").expect("json") )); live.send(&format!( r#"{{"jsonrpc":"2.0","id":4,"method":"textDocument/diagnostic","params":{{"textDocument":{{"uri":"{uri}"}},"identifier":"lucisv","previousResultId":"{result_id}"}}}}"# )); let after = live.wait_for(|m| m["id"] == 4 || m["method"] == "textDocument/publishDiagnostics"); assert_eq!(after["id"], 4, "still no push: {after:#?}"); assert_eq!(after["result"]["kind"], "full", "{after:#?}"); assert_eq!(after["result"]["items"].as_array().map(Vec::len), Some(0), "{after:#?}"); // And the workspace report names the open buffer. live.send( r#"{"jsonrpc":"2.0","id":5,"method":"workspace/diagnostic","params":{"identifier":"lucisv","previousResultIds":[]}}"#, ); let workspace = live.wait_for(|m| m["id"] == 5); let items = workspace["result"]["items"].as_array().expect("items"); assert_eq!(items.len(), 1, "one open buffer: {workspace:#?}"); assert_eq!(items[0]["uri"], uri.as_str(), "{workspace:#?}"); assert_eq!(items[0]["kind"], "full", "{workspace:#?}"); live.finish(); let _ = std::fs::remove_dir_all(&dir); } #[test] fn a_command_pushes_its_edit_to_a_client_that_can_apply_one() { // The bug ยง9a fixes, checked where it actually bit: on the wire, against // a client that says what `vscode-languageclient` says. let dir = temp_dir("applyedit"); let sub = dir.join("sub.sv"); std::fs::write(&sub, PORTS_SUB).expect("write"); let top = dir.join("top.sv"); std::fs::write(&top, PORTS_TOP).expect("write"); let root = format!("file://{}", dir.display()); let top_uri = format!("file://{}", top.display()); let mut live = Live::start(); live.send(&format!( r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{"workspace":{{"applyEdit":true}}}}}}}}"# )); live.wait_for(|m| m["id"] == 1); live.send(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#); live.send(&format!( r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{top_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, serde_json::to_string(PORTS_TOP).expect("json") )); live.send(&format!( r#"{{"jsonrpc":"2.0","id":2,"method":"workspace/executeCommand","params":{{"command":"lucisv.propagatePorts","arguments":["{top_uri}",{{"line":2,"character":6}}]}}}}"# )); // The push, before the command's own answer. let push = live.wait_for(|m| m["method"] == "workspace/applyEdit"); assert_eq!(push["params"]["label"], "lucisv: lucisv.propagatePorts", "{push:#?}"); let edits = push["params"]["edit"]["changes"][&top_uri].as_array().expect("edits"); assert_eq!(edits[0]["newText"], ", .rst(rst)", "{push:#?}"); // Answer it the way an editor does, and the command answers `null`. let id = serde_json::to_string(&push["id"]).expect("json"); live.send(&format!(r#"{{"jsonrpc":"2.0","id":{id},"result":{{"applied":true}}}}"#)); let done = live.wait_for(|m| m["id"] == 2); assert!(done["result"].is_null(), "the edit is not the result any more: {done:#?}"); live.finish(); let _ = std::fs::remove_dir_all(&dir); } #[test] fn selection_ranges_round_trip_over_the_wire() { // What only an e2e test can check: the capability is advertised, and the // linked chain survives JSON encoding as `parent` objects rather than as // a flattened list. let dir = temp_dir("selection"); let file = dir.join("m.sv"); let source = "module m;\n initial begin\n x = 1;\n end\nendmodule\n"; std::fs::write(&file, source).expect("write"); let root = format!("file://{}", dir.display()); let uri = format!("file://{}", file.display()); let session = [ frame(&format!( r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"# )), frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), frame(&format!( r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, serde_json::to_string(source).expect("json") )), // Two cursors: the `x` of `x = 1;`, and the `endmodule` line. frame(&format!( r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/selectionRange","params":{{"textDocument":{{"uri":"{uri}"}},"positions":[{{"line":2,"character":4}},{{"line":4,"character":0}}]}}}}"# )), frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), ] .concat(); let messages = talk(&session); let initialize = messages.iter().find(|m| m["id"] == 1).expect("initialize response"); assert_eq!( initialize["result"]["capabilities"]["selectionRangeProvider"], serde_json::json!(true), "{initialize:#?}" ); let response = messages.iter().find(|m| m["id"] == 2).expect("selectionRange response"); let chains = response["result"].as_array().expect("one chain per position"); assert_eq!(chains.len(), 2, "{response:#?}"); // The `x`, then its statement, then the block, then the module, then the // file โ€” each step wider than the last, and the last one whole-file. let mut step = &chains[0]; let mut widths = Vec::new(); loop { widths.push(( step["range"]["start"]["line"].as_u64().expect("line"), step["range"]["end"]["line"].as_u64().expect("line"), )); match step.get("parent") { Some(parent) if parent.is_object() => step = parent, _ => break, } } assert!(widths.len() >= 4, "token, statement, block, module, file: {widths:?}"); assert_eq!(widths[0], (2, 2), "the innermost step is on the cursor's own line"); assert_eq!(widths.last(), Some(&(0, 5)), "and the file closes it: {widths:?}"); let _ = std::fs::remove_dir_all(&dir); } /// A clean buffer with a multi-byte comment above the line the edits touch: /// a byte-vs-UTF-16 confusion in the sync path would land them on the wrong /// columns, and the diagnostics at the end would say so. const SYNCABLE: &str = "// รฉ โœ“ ๐ŸŽ‰\nmodule sync_me;\n wire a;\nendmodule\n"; #[test] fn incremental_changes_are_advertised_and_applied_over_the_wire() { let dir = temp_dir("incremental"); let file = dir.join("sync_me.sv"); std::fs::write(&file, SYNCABLE).expect("write"); let root = format!("file://{}", dir.display()); let uri = format!("file://{}", file.display()); // Three ranges in one notification, each positioned against what the // previous one left: delete the `a`, which breaks the buffer; type a `b` // back in, which fixes it; then open a new, broken declaration below. // A second notification finishes that declaration, badly spaced, so a // formatting request can read the composed buffer back off the wire. let session = [ frame(&format!( r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"# )), frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), frame(&format!( r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, serde_json::to_string(SYNCABLE).expect("json") )), frame(&format!( r#"{{"jsonrpc":"2.0","method":"textDocument/didChange","params":{{"textDocument":{{"uri":"{uri}","version":2}},"contentChanges":[{}]}}}}"#, [ r#"{"range":{"start":{"line":2,"character":7},"end":{"line":2,"character":8}},"text":""}"#, r#"{"range":{"start":{"line":2,"character":7},"end":{"line":2,"character":7}},"text":"b"}"#, r#"{"range":{"start":{"line":3,"character":0},"end":{"line":3,"character":0}},"text":" wire ;\n"}"#, ] .join(",") )), frame(&format!( r#"{{"jsonrpc":"2.0","method":"textDocument/didChange","params":{{"textDocument":{{"uri":"{uri}","version":3}},"contentChanges":[{}]}}}}"#, r#"{"range":{"start":{"line":3,"character":9},"end":{"line":3,"character":9}},"text":"c"}"# )), frame(&format!( r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/formatting","params":{{"textDocument":{{"uri":"{uri}"}},"options":{{"tabSize":2,"insertSpaces":true}}}}}}"# )), frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), ] .concat(); let messages = talk(&session); // 1. The capability says incremental, and says the rest explicitly. let initialize = messages.iter().find(|m| m["id"] == 1).expect("initialize response"); let sync = &initialize["result"]["capabilities"]["textDocumentSync"]; assert_eq!(sync["change"], 2, "TextDocumentSyncKind::Incremental: {initialize:#?}"); assert_eq!(sync["openClose"], true, "{sync:#?}"); assert_eq!(sync["save"]["includeText"], false, "a save re-sends nothing: {sync:#?}"); // 2. Each notification published once, and what it published describes // the composed buffer: the error is on the line the third range // inserted, and it clears when the fourth range finishes that line. let published: Vec<_> = messages.iter().filter(|m| m["method"] == "textDocument/publishDiagnostics").collect(); assert_eq!(published.len(), 3, "one per notification, not one per range: {published:#?}"); assert!( published[0]["params"]["diagnostics"].as_array().expect("an array").is_empty(), "the file opened clean: {published:#?}" ); let diagnostics = published[1]["params"]["diagnostics"].as_array().expect("an array"); assert_eq!(diagnostics.len(), 1, "{diagnostics:#?}"); assert_eq!(diagnostics[0]["range"]["start"]["line"], 3, "the inserted line"); assert!( published[2]["params"]["diagnostics"].as_array().expect("an array").is_empty(), "and the next range fixed it: {published:#?}" ); // 3. And the buffer the server holds is exactly the composed text โ€” read // back through the formatter, which normalizes only the spacing the // last range left behind. assert_eq!( new_text(&messages, 2), "// รฉ โœ“ ๐ŸŽ‰\nmodule sync_me;\n wire b;\n wire c;\nendmodule\n", "the four ranges composed, and the emoji line untouched" ); let _ = std::fs::remove_dir_all(&dir); }