Files
lucisv/crates/lucisv_server/tests/e2e.rs
T
lucioandClaude Fable 5 4e62a14af6 Fragment mode and define continuation: the three .svh shapes that did not parse, and the define that was blamed on its class body
TODO section 22, coverage_gaps H4 corrected. Class-body and module-item
include fragments already parsed - the file-scope item loop is the
class-item loop. The three shapes that did not - a bare statement list,
an enum-member list (riscv-dv's CUSTOM_1, file, included between enum
members), a covergroup-item list - become SourceFile::fragment, detected
by a whole-file rule that cannot misfire on a valid file: the first
structural item failed (directives, macros and null items do not count;
a tolerant Ok that recorded a diagnostic counts as failed - an existing
parity test caught if/else reading as a generate-if to one parser and a
statement to the other), the file does not open with a design-unit
keyword, and a shape consumes the file to EOF, tried narrowest-first.
Each shape re-lexes a fresh token stream - Rewind does not restore the
tokens' comment buckets and the first draft lost comments on
non-fragment files. A fragment formats at indent zero through the
existing printers; its declarations bind; its enum variants are not
exported (pkg::CUSTOM_1 must not resolve to a name that does not
exist). FACTS stays 12.

The other .svh was never a fragment problem: a define whose formal
argument list spans two lines with no backslash. The lexer continues
such a directive until the list closes - incrementally, after QA found
the first cut quadratic on an unclosed list (20000 lines: 2.5 s ->
0.56 ms), pinned by a byte-visit counter.

Opentitan 12 -> 10 failing files, exactly the two predicted; corpus
813 -> 814 of 820; every remaining comment-gap failure proven to fail
identically outside a fragment.

docs/features/fragment-mode/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 07:34:31 -07:00

7237 lines
340 KiB
Rust

//! 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())
}
/// The `didChangeConfiguration` push that asks for the whole-workspace index
/// scope — what every session had before 2026-08-27.
///
/// Sessions whose subject is *not* the scope send it right after
/// `initialized`: the default scope is the folders the client's own buffers
/// live in, so a session that opens no buffer (or that expects a folder it
/// never opened a file in to be indexed) would otherwise be asking questions
/// of an empty index. See `docs/features/index-scope/README.md`.
const WIDE_SCOPE: &str = r#"{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{"settings":{"lucisv":{"index":{"scope":"workspace"}}}}}"#;
/// Split a stdout dump into its JSON payloads.
fn unframe(mut input: impl BufRead) -> Vec<serde_json::Value> {
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<serde_json::Value> {
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::<usize>().ok();
}
}
let mut body = vec![0u8; length?];
input.read_exact(&mut body).ok()?;
serde_json::from_slice(&body).ok()
}
/// The server binary, with its OS cache directory pointed somewhere a test
/// may write.
///
/// Without a client-supplied `storagePath` the persistent index cache falls
/// back to this platform's cache directory
/// (`docs/features/index-persistence/README.md`), and the developer's own
/// `~/Library/Caches` is not somewhere a test run may leave anything. The
/// three variables below are the ones that decide it on the three platforms.
/// A test whose subject *is* the cache passes a `storagePath` of its own,
/// which outranks all of them.
fn server_command() -> Command {
let sandbox =
std::env::temp_dir().join(format!("lucisv_server_e2e_home_{}", std::process::id()));
let mut command = Command::new(env!("CARGO_BIN_EXE_lucisv-server"));
command
.env("HOME", &sandbox)
.env("XDG_CACHE_HOME", sandbox.join("cache"))
.env("LOCALAPPDATA", sandbox.join("cache"));
command
}
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<serde_json::Value> {
talk_with(&[], session)
}
/// [`talk`] with arguments on the spawn.
///
/// The no-argument spawn above is the contract every editor uses and
/// `smoke.js` drives; this is for the one argument the server takes,
/// `--verbose` (`docs/features/verbose-timing/README.md`).
fn talk_with(args: &[&str], session: &str) -> Vec<serde_json::Value> {
let mut child = server_command()
.args(args)
.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<serde_json::Value> {
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);
}
/// Four items on four lines, so two ranges can straddle one they leave alone.
const FOUR_ITEMS: &str = "module m;\n wire a;\n wire b;\n wire c;\nendmodule\n";
#[test]
fn ranges_formatting_is_advertised_to_a_client_that_asked_and_formats_every_range() {
// The 3.18 leg, over the real wire: the capability is only widened for a
// client that sent `rangesSupport`, and the request that widening unlocks
// lays out every range it names in one answer.
let dir = temp_dir("rangesfmt");
let file = dir.join("m.sv");
std::fs::write(&file, FOUR_ITEMS).expect("write");
let root = format!("file://{}", dir.display());
let uri = format!("file://{}", file.display());
let ranges = |id: u32, ranges: &str| {
frame(&format!(
r#"{{"jsonrpc":"2.0","id":{id},"method":"textDocument/rangesFormatting","params":{{"textDocument":{{"uri":"{uri}"}},"ranges":{ranges},"options":{{"tabSize":2,"insertSpaces":true}}}}}}"#
))
};
let line = |n: u32| {
format!(
r#"{{"start":{{"line":{n},"character":0}},"end":{{"line":{},"character":0}}}}"#,
n + 1
)
};
let session = [
// The 3.18 client, saying so exactly as `vscode-languageclient` does.
frame(&format!(
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{"textDocument":{{"rangeFormatting":{{"dynamicRegistration":true,"rangesSupport":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(FOUR_ITEMS).expect("json")
)),
// Lines 2 and 4, leaving 3 alone — and sent *unsorted*, which the
// server must normalize rather than take in the order it arrived.
ranges(2, &format!("[{},{}]", line(3), line(1))),
// An empty ask is answered, not refused.
ranges(3, "[]"),
// Every line at once is the whole-file format.
ranges(4, &format!("[{},{},{},{},{}]", line(0), line(1), line(2), line(3), line(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");
assert_eq!(
initialize["result"]["capabilities"]["documentRangeFormattingProvider"],
serde_json::json!({ "rangesSupport": true }),
"a client that asked gets the options object, not the bare `true`"
);
assert_eq!(
new_text(&messages, 2),
"module m;\n wire a;\n wire b;\n wire c;\nendmodule\n",
"both named lines laid out, the one between them byte-for-byte"
);
let empty = messages.iter().find(|m| m["id"] == 3).expect("response");
assert_eq!(empty["result"].as_array().expect("an array").len(), 0, "an empty ask");
assert!(empty["error"].is_null(), "and never an error: {empty:#?}");
assert_eq!(
new_text(&messages, 4),
"module m;\n wire a;\n wire b;\n wire c;\nendmodule\n",
"every line named is a whole-file format"
);
// Nothing was said to the user on any of the three.
assert!(
!messages.iter().any(|m| m["method"] == "window/showMessage"),
"a clean buffer and a clean config say nothing: {messages:#?}"
);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_3_17_client_still_sees_the_bare_true_it_always_saw() {
// The gate, over the wire: a client that did not advertise `rangesSupport`
// must see the capability byte-for-byte as it was before this round — and
// is still answered if it sends the request anyway.
let dir = temp_dir("rangesfmt317");
let file = dir.join("m.sv");
std::fs::write(&file, FOUR_ITEMS).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":{{"textDocument":{{"rangeFormatting":{{"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(FOUR_ITEMS).expect("json")
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/rangesFormatting","params":{{"textDocument":{{"uri":"{uri}"}},"ranges":[{{"start":{{"line":1,"character":0}},"end":{{"line":2,"character":0}}}}],"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);
let initialize = messages.iter().find(|m| m["id"] == 1).expect("initialize response");
assert_eq!(
initialize["result"]["capabilities"]["documentRangeFormattingProvider"],
serde_json::json!(true),
"unchanged for every client that shipped before this round"
);
assert_eq!(
new_text(&messages, 2),
"module m;\n wire a;\n wire b;\n wire c;\nendmodule\n",
"the handler is registered unconditionally; only the advertising is gated"
);
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<PathBuf> {
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 typing_a_newline_and_a_semicolon_round_trips_over_the_real_binary() {
// Simulates the two keystrokes the client actually sends, in order, with
// the `didChange` between them that a real editor would send: type a
// newline inside a block (the buffer grows a blank line), apply the indent,
// then finish a statement with `;`.
let dir = temp_dir("ontype");
let file = dir.join("m.sv");
let opened = "module m;\n always_comb begin\n end\nendmodule\n";
std::fs::write(&file, opened).expect("write");
let root = format!("file://{}", dir.display());
let uri = format!("file://{}", file.display());
// What the buffer holds after the user pressed Enter at the end of the
// `begin` line: one blank line, no indentation on it yet.
let after_newline = "module m;\n always_comb begin\n\n end\nendmodule\n";
// ...and after the client applied the indent and typed a statement whose
// spacing the formatter would tighten.
let after_typing = "module m;\n always_comb begin\n x = 1;\n end\nendmodule\n";
let full_change = |version: u32, text: &str| {
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didChange","params":{{"textDocument":{{"uri":"{uri}","version":{version}}},"contentChanges":[{{"text":{}}}]}}}}"#,
serde_json::to_string(text).expect("json")
))
};
let on_type = |id: u32, ch: &str, line: u32, character: u32| {
frame(&format!(
r#"{{"jsonrpc":"2.0","id":{id},"method":"textDocument/onTypeFormatting","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":{line},"character":{character}}},"ch":{},"options":{{"tabSize":2,"insertSpaces":true}}}}}}"#,
serde_json::to_string(ch).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":{}}"#),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string(opened).expect("json")
)),
full_change(2, after_newline),
on_type(2, "\n", 2, 0),
full_change(3, after_typing),
on_type(3, ";", 2, 14),
// A trigger this server never advertised, over the wire: still `[]`.
on_type(4, "}", 2, 14),
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 options = &initialize["result"]["capabilities"]["documentOnTypeFormattingProvider"];
assert_eq!(options["firstTriggerCharacter"], "\n", "on the wire: {options:#?}");
assert_eq!(
options["moreTriggerCharacter"],
serde_json::json!([";"]),
"and the semicolon with it: {options:#?}"
);
let indent = messages.iter().find(|m| m["id"] == 2).expect("a response to the newline");
let edits = indent["result"].as_array().expect("an array of edits");
assert_eq!(edits.len(), 1, "{indent:#?}");
assert_eq!(edits[0]["newText"], " ", "the block's own level: {indent:#?}");
assert_eq!(edits[0]["range"]["end"]["character"], 0, "and only whitespace replaced");
assert_eq!(
new_text(&messages, 3),
"module m;\n always_comb begin\n x = 1;\n end\nendmodule\n",
"the `;` laid out the statement it ended"
);
let unknown = messages.iter().find(|m| m["id"] == 4).expect("a response to the `}`");
assert_eq!(unknown["result"], serde_json::json!([]), "{unknown:#?}");
assert!(
!messages.iter().any(|m| m["method"] == "window/showMessage"),
"a keystroke never speaks: {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}"}}}}"#
))
};
// Every push carries `index.scope: "workspace"`: this test is about the
// filelist rung and the walk it falls back to, and a push replaces every
// setting — without it each message would also move the fallback to the
// folder scope, which no buffer has widened here.
let filelist = |path: &str| {
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{{"settings":{{"lucisv":{{"filelist":"{path}","index":{{"scope":"workspace"}}}}}}}}}}"#
))
};
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":{}}"#),
// The walk this test starts from is the opt-in one now.
filelist(""),
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");
// Changed 2026-08-28 with the shipped `scopeDepth` of 2. A rootless
// session still does not *climb* — there is no workspace root to clamp a
// climb against, so `raised` leaves the buffer's own directory alone — but
// a non-zero depth still asks for a walk rather than a flat read, so the
// subtree under that one directory is now indexed. Bounded by the
// directory the user opened a file from, and no wider.
assert_eq!(hits(4), 1, "the depth asks for a walk of that 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 module's **name**
// — the instantiation is ghost text now, and
// `the_module_name_completes_and_the_ghost_finishes_it_over_the_wire`
// below carries on from exactly here.
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"], 1, "InsertTextFormat.PlainText");
let new_text = item["textEdit"]["newText"].as_str().expect("newText");
assert_eq!(new_text, "hint_sub", "the name alone; the ports arrive as ghost text");
assert_eq!(item["textEdit"]["range"]["start"]["character"], 2, "the typed word is replaced");
assert_eq!(item["textEdit"]["range"]["end"]["character"], 8);
// Nothing multi-line is inserted any more, so there is no indentation to
// defend from the editor's adjustment.
assert!(item["insertTextMode"].is_null(), "a word needs no insertTextMode: {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. Since 2026-08-30 the module item is a plain word for *every*
/// client, so this pins that the answer no longer depends on the flag at all.
#[test]
fn a_client_without_snippet_support_gets_the_same_module_name_item() {
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_eq!(new_text, "hint_sub", "the same word the snippet client is offered");
let _ = std::fs::remove_dir_all(&dir);
}
/// The two levels, joined: complete the name, apply the edit the popup sent,
/// type the space that arms the ghost, and ask for an inline completion. What
/// comes back is the whole instantiation.
///
/// "Before or after autocomplete" — the ghost is keyed on the *text*, not on
/// having accepted an item, so the second half of this test is what a user who
/// typed `hint_sub ` themselves would see too. The cursor landing straight off
/// the popup, with no space yet, is the round-2 ruling and gets `null`: the
/// name may still be growing into a longer one.
#[test]
fn the_module_name_completes_and_the_ghost_finishes_it_over_the_wire() {
let dir = temp_dir("hintghost");
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());
// What the buffer holds once the popup's `hint_sub` textEdit has replaced
// the half-typed `hint_s` on line 2 — the client's own job, done here by
// hand so the cursor really is where accepting an item leaves it.
let accepted = "module hint_top;\n logic clk;\n hint_sub\nendmodule\n";
// …and what it holds one keystroke later, when the space that arms the
// ghost has been typed.
let armed = "module hint_top;\n logic clk;\n hint_sub \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}}}},"inlineCompletion":{{"dynamicRegistration":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 popup, at the end of the half-typed ` hint_s`.
frame(&format!(
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/completion","params":{{"textDocument":{{"uri":"{top_uri}"}},"position":{{"line":2,"character":8}}}}}}"#
)),
// The client applies the edit…
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didChange","params":{{"textDocument":{{"uri":"{top_uri}","version":2}},"contentChanges":[{{"text":{}}}]}}}}"#,
serde_json::to_string(accepted).expect("json")
)),
// …and the ghost is asked for where the cursor landed: line 2,
// character 10, the end of ` hint_sub`. Nothing yet — the name is
// spelled but not finished.
frame(&format!(
r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/inlineCompletion","params":{{"textDocument":{{"uri":"{top_uri}"}},"position":{{"line":2,"character":10}},"context":{{"triggerKind":2}}}}}}"#
)),
// The user types one space…
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didChange","params":{{"textDocument":{{"uri":"{top_uri}","version":3}},"contentChanges":[{{"text":{}}}]}}}}"#,
serde_json::to_string(armed).expect("json")
)),
// …and asks again from where that space left the cursor: character 11.
frame(&format!(
r#"{{"jsonrpc":"2.0","id":4,"method":"textDocument/inlineCompletion","params":{{"textDocument":{{"uri":"{top_uri}"}},"position":{{"line":2,"character":11}},"context":{{"triggerKind":2}}}}}}"#
)),
// The same buffer, cursor back at the end of the name itself: still
// nothing, because the rule is about the byte before the cursor and
// not about what the line happens to contain.
frame(&format!(
r#"{{"jsonrpc":"2.0","id":5,"method":"textDocument/inlineCompletion","params":{{"textDocument":{{"uri":"{top_uri}"}},"position":{{"line":2,"character":10}},"context":{{"triggerKind":2}}}}}}"#
)),
// One character short of the name is not the name either.
frame(&format!(
r#"{{"jsonrpc":"2.0","id":6,"method":"textDocument/inlineCompletion","params":{{"textDocument":{{"uri":"{top_uri}"}},"position":{{"line":2,"character":9}},"context":{{"triggerKind":2}}}}}}"#
)),
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 popup's item is the name, and applying it is what produced the
// buffer the ghost is asked about.
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:#?}"));
let edit = &item["textEdit"];
assert_eq!(edit["newText"], "hint_sub");
let mut applied = String::from(HINT_TOP);
let line = applied.find(" hint_s").expect("the half-typed line") + 2;
applied.replace_range(line..line + 6, edit["newText"].as_str().expect("newText"));
assert_eq!(applied, accepted, "the didChange above is what applying the edit produces");
// 2. The landing cursor itself, with no space typed yet: nothing. Owner
// ruling, 2026-08-30 — `hint_sub` may still be on its way to
// `hint_sub_dft`, and only the space says it is not.
let unarmed = messages.iter().find(|m| m["id"] == 3).expect("inlineCompletion response");
assert_eq!(
unarmed["result"],
serde_json::Value::Null,
"the name alone is not a commitment to instantiate"
);
// 3. One space later: parameters, ports, tabstops, and the relative `\t`
// indentation the inline contract requires — with the arming space cut
// off the front along with the name.
let ghost = messages.iter().find(|m| m["id"] == 4).expect("inlineCompletion response");
assert_eq!(
ghost["result"],
serde_json::json!({
"items": [{
"insertText": {
"kind": "snippet",
"value": "#(\n\t.WIDTH(${1:8})\n) ${2:u_hint_sub} (\n\t.clk(clk),\n\t.data(${3:data}),\n\t.ready(${4:ready})\n);"
},
"range": {
"start": { "line": 2, "character": 11 },
"end": { "line": 2, "character": 11 }
}
}]
}),
"the name and its space are cut off the front; `clk` is in scope and binds itself"
);
// 4. The cursor put back at the end of the name in that same buffer: the
// byte before the cursor is `b`, not a space, so still nothing.
let back = messages.iter().find(|m| m["id"] == 5).expect("inlineCompletion response");
assert_eq!(back["result"], serde_json::Value::Null, "the space has to be the one just typed");
// 5. One character short of the whole name is not the whole name.
let partial = messages.iter().find(|m| m["id"] == 6).expect("inlineCompletion response");
assert_eq!(partial["result"], serde_json::Value::Null, "`hint_su` is not a module");
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);
}
/// `lucisv.inlineInstantiation`, the same way — and the same link a unit test
/// cannot check, since `inline.rs`'s own tests set the settings directly.
#[test]
fn the_inline_instantiation_setting_is_honoured_over_the_wire() {
let dir = temp_dir("inst_setting");
std::fs::write(dir.join("hint_sub.sv"), HINT_SUB).expect("write");
// The name and the space that arms the ghost, which is what line 2 has to
// hold for there to be an offer for the setting to suppress.
let top = "module hint_top;\n logic clk;\n hint_sub \nendmodule\n";
let path = dir.join("hint_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":2,"character":11}},"context":{{"triggerKind":2}}}}}}"#
))
};
let push = |setting: &str| {
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{{"settings":{{"lucisv":{{"inlineInstantiation":{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, "inlineInstantiation: false suppresses it");
assert_ne!(items(4), serde_json::Value::Null, "inlineInstantiation: 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);
}
/// Fuzzy completion over the wire, and the transition that makes it reachable
/// at all.
///
/// Three requests against one buffer, at two, three and six typed characters.
/// The two-character answer has to come back `isIncomplete: true` or VS Code
/// filters the list it holds for the rest of the word and the third keystroke
/// — the one that turns subsequence matching on — never reaches the server.
/// See `docs/features/fuzzy-completion/README.md`.
#[test]
fn fuzzy_completion_round_trips_over_the_wire_including_the_two_to_three_transition() {
let dir = temp_dir("fuzzy");
std::fs::write(
dir.join("ast.sv"),
"module ast;\n logic clk_osc_en_q;\n logic c_l_k_scatter;\n logic celsius;\n\
endmodule\n",
)
.expect("write");
// Three buffers' worth of typing in one file, one per line, so one
// session can ask about all three without a `didChange`.
let top = "module top;\n assign a = ce\n assign b = clk\n assign c = clkenq\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/completion","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(top).expect("json")
)),
// End of `ce` on line 1, `clk` on line 2, `clkenq` on line 3.
ask(2, 1, 15),
ask(3, 2, 16),
ask(4, 3, 19),
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 answer = |id: u32| {
messages.iter().find(|m| m["id"] == id).unwrap_or_else(|| panic!("completion {id}"))
};
let labels = |id: u32| -> Vec<String> {
answer(id)["result"]["items"]
.as_array()
.unwrap_or_else(|| panic!("no completion list in {:#?}", answer(id)))
.iter()
.map(|item| item["label"].as_str().expect("a label").to_string())
.collect()
};
// Two characters: prefix only, and — the whole point — incomplete, so the
// client comes back on the third keystroke.
let two = labels(2);
assert!(two.contains(&"celsius".to_string()), "{two:?}");
assert!(!two.contains(&"clk_osc_en_q".to_string()), "`ce` is not a prefix of it: {two:?}");
assert_eq!(
answer(2)["result"]["isIncomplete"],
serde_json::Value::Bool(true),
"a two-character answer must ask to be asked again"
);
// Three: subsequence matching is on, and the prefix hit leads the scatter.
let three = labels(3);
let at = |list: &[String], label: &str| {
list.iter().position(|held| held == label).unwrap_or_else(|| panic!("{label} in {list:?}"))
};
assert!(at(&three, "clk_osc_en_q") < at(&three, "c_l_k_scatter"), "{three:?}");
// Six: the name the round is about, reached by letters no prefix holds,
// replacing exactly the six characters that were typed.
let six = answer(4)["result"]["items"].as_array().expect("a completion list").clone();
let hit = six
.iter()
.find(|item| item["label"] == "clk_osc_en_q")
.unwrap_or_else(|| panic!("clkenq did not reach it: {:?}", labels(4)));
assert_eq!(hit["textEdit"]["newText"], "clk_osc_en_q");
assert_eq!(hit["textEdit"]["range"]["start"], serde_json::json!({"line": 3, "character": 13}));
assert_eq!(hit["textEdit"]["range"]["end"], serde_json::json!({"line": 3, "character": 19}));
assert!(hit["filterText"].is_null(), "the client filters on the label: {hit:#?}");
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}}}}}}"#
)),
// `performance.md` §7: documentHighlight answered `null` at every
// opentitan position tried — an instantiated module's name and a port
// connection — while `references` (id 2 above, same position)
// answered. Both are names declared in the *other* file.
frame(&format!(
r#"{{"jsonrpc":"2.0","id":6,"method":"textDocument/documentHighlight","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":2,"character":2}}}}}}"#
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":7,"method":"textDocument/documentHighlight","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":2,"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 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");
// The two positions `performance.md` reported as answering nothing.
let starts = |id: u32| -> Vec<(u64, u64)> {
response(id)["result"]
.as_array()
.unwrap_or_else(|| panic!("response {id} answered nothing: {:#?}", response(id)))
.iter()
.map(|h| {
(
h["range"]["start"]["line"].as_u64().expect("line"),
h["range"]["start"]["character"].as_u64().expect("character"),
)
})
.collect()
};
assert_eq!(starts(6), vec![(2, 2)], "the instantiated module's name, declared in sub.sv");
assert_eq!(starts(7), vec![(2, 12)], "the `.clk` port name, declared in sub.sv");
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<std::process::ChildStdout>,
}
impl Live {
fn start() -> Live {
let mut child = server_command()
.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:#?}");
}
/// Shut the session down, and say how many `publishDiagnostics` arrived
/// on the way out.
///
/// The count is what lets a measurement tell one flush from ten: a
/// buffer left dirty by a burst is flushed before the next *request* is
/// answered, so every publish a burst was going to produce has arrived by
/// the time `shutdown` comes back. Most callers ignore the number.
fn finish(mut self) -> usize {
let published = std::cell::Cell::new(0usize);
self.send(r#"{"jsonrpc":"2.0","id":99,"method":"shutdown","params":null}"#);
self.wait_for(|m| {
if m["method"] == "textDocument/publishDiagnostics" {
published.set(published.get() + 1);
}
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:?}");
published.get()
}
}
#[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 = &registration["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(&registration["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::<serde_json::Value>(&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(WIDE_SCOPE),
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(WIDE_SCOPE),
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);
}
/// TODO.md §22: a file that is nothing but the middle of an `enum` body —
/// riscv-dv's `riscv_custom_instr_enum.sv`, `` `include``d between two members
/// of `riscv_instr_pkg`'s enum. Before fragment mode the whole file was one
/// error node: hover said nothing and the buffer carried a parse diagnostic
/// for code that is perfectly good where it is included. Both halves are
/// pinned here, over the wire.
#[test]
fn an_enum_variant_in_a_fragment_file_hovers_and_reports_no_diagnostics() {
let dir = temp_dir("fragment");
let file = dir.join("riscv_custom_instr_enum.sv");
let text = "// TODO: Add custom instruction name enum\nCUSTOM_1,\n";
std::fs::write(&file, text).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(text).expect("json")
)),
// The cursor inside `CUSTOM_1` on line 1.
frame(&format!(
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/hover","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":1,"character":3}}}}}}"#
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/documentSymbol","params":{{"textDocument":{{"uri":"{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 hover = messages
.iter()
.find(|m| m["id"] == 2)
.unwrap_or_else(|| panic!("no hover response: {messages:#?}"));
let card = hover["result"]["contents"]["value"].as_str().expect("hover markdown");
assert!(card.contains("enum variant"), "the fragment's member is an enum variant: {card:?}");
assert!(card.contains("CUSTOM_1"), "{card:?}");
// Every diagnostics push for this file must be empty: the file parses.
let published: Vec<&serde_json::Value> = messages
.iter()
.filter(|m| m["method"] == "textDocument/publishDiagnostics")
.filter(|m| m["params"]["uri"] == serde_json::Value::String(uri.clone()))
.collect();
for push in &published {
assert_eq!(
push["params"]["diagnostics"].as_array().map(Vec::len),
Some(0),
"a fragment file is not a broken file: {push:#?}"
);
}
// And it has an outline, which is what tells an editor the file is
// understood rather than skipped.
let outline = messages
.iter()
.find(|m| m["id"] == 3)
.unwrap_or_else(|| panic!("no documentSymbol response: {messages:#?}"));
assert!(
format!("{outline:#?}").contains("CUSTOM_1"),
"the variant belongs in the outline: {outline:#?}"
);
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. The changes were coalesced: both notifications arrived before
// anything needed their analysis, so one flush published the composed
// buffer once — clean, because the fourth range finished the line the
// third inserted. An intermediate publish of the broken half-state is
// what the change debounce removed; what is drawn is always a state
// the buffer actually passed through, just fewer of them.
let published: Vec<_> =
messages.iter().filter(|m| m["method"] == "textDocument/publishDiagnostics").collect();
assert_eq!(published.len(), 2, "one for the open, one for the flushed changes: {published:#?}");
assert!(
published[0]["params"]["diagnostics"].as_array().expect("an array").is_empty(),
"the file opened clean: {published:#?}"
);
assert!(
published[1]["params"]["diagnostics"].as_array().expect("an array").is_empty(),
"and the composed buffer is clean: {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);
}
/// The client's side of a delta: splice each edit into the flat array it
/// holds, by index. Shares nothing with the server's own code.
fn apply_token_edits(previous: &[u64], answer: &serde_json::Value) -> Vec<u64> {
let mut data = previous.to_vec();
let edits = answer["edits"].as_array().unwrap_or_else(|| panic!("edits in {answer:#?}"));
for edit in edits {
let start = edit["start"].as_u64().expect("start") as usize;
let end = start + edit["deleteCount"].as_u64().expect("deleteCount") as usize;
let inserted = edit.get("data").map(token_numbers).unwrap_or_default();
data.splice(start..end, inserted);
}
data
}
/// A semantic-token `data` array as flat numbers.
fn token_numbers(value: &serde_json::Value) -> Vec<u64> {
value
.as_array()
.unwrap_or_else(|| panic!("an array of numbers, got {value:#?}"))
.iter()
.map(|n| n.as_u64().expect("a number"))
.collect()
}
#[test]
fn semantic_tokens_range_and_delta_round_trip_over_the_wire() {
// What a unit test cannot check: that both new capabilities reach the
// wire in the shape a client keys off, and that a real delta — computed
// by one process and applied by another, over the wire's flat number
// array — reconstructs the token set the next full request answers.
let dir = temp_dir("semantictokens");
let file = dir.join("m.sv");
let before = "module tokens_me;\n localparam W = 8;\n wire [W-1:0] a;\nendmodule\n";
let after =
"module tokens_me;\n localparam W = 16;\n wire [W-1:0] a;\n // added\nendmodule\n";
std::fs::write(&file, before).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(before).expect("json")
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/semanticTokens/full","params":{{"textDocument":{{"uri":"{uri}"}}}}}}"#
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/semanticTokens/range","params":{{"textDocument":{{"uri":"{uri}"}},"range":{{"start":{{"line":1,"character":0}},"end":{{"line":2,"character":0}}}}}}}}"#
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didChange","params":{{"textDocument":{{"uri":"{uri}","version":2}},"contentChanges":[{{"text":{}}}]}}}}"#,
serde_json::to_string(after).expect("json")
)),
// The ids are minted one per answer from the start of the session, so
// the full answer above is `"1"` — asserted below, so a changed
// scheme fails loudly here rather than silently downgrading every
// delta to a full answer.
frame(&format!(
r#"{{"jsonrpc":"2.0","id":4,"method":"textDocument/semanticTokens/full/delta","params":{{"textDocument":{{"uri":"{uri}"}},"previousResultId":"1"}}}}"#
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":5,"method":"textDocument/semanticTokens/full","params":{{"textDocument":{{"uri":"{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);
// 1. Both capabilities on the wire, in the shape a client reads.
let initialize = messages.iter().find(|m| m["id"] == 1).expect("initialize response");
let provider = &initialize["result"]["capabilities"]["semanticTokensProvider"];
assert_eq!(provider["range"], true, "range is advertised: {provider:#?}");
assert_eq!(provider["full"]["delta"], true, "and so are deltas: {provider:#?}");
assert_eq!(
provider["legend"]["tokenTypes"].as_array().expect("the legend").len(),
14,
"the legend is unchanged: {provider:#?}"
);
// 2. The full answer is stamped, and its id is the one the delta named.
let full = messages.iter().find(|m| m["id"] == 2).expect("full response");
assert_eq!(full["result"]["resultId"], "1", "{full:#?}");
let held = token_numbers(&full["result"]["data"]);
assert!(!held.is_empty(), "{full:#?}");
// 3. The range answer stands on its own: no id, absolute first delta.
let ranged = messages.iter().find(|m| m["id"] == 3).expect("range response");
assert!(ranged["result"].get("resultId").is_none(), "nothing to name: {ranged:#?}");
let window = token_numbers(&ranged["result"]["data"]);
assert_eq!(window[0], 1, "deltaLine is absolute from the file start: {ranged:#?}");
assert!(window.len() < held.len(), "and it is only part of the file: {ranged:#?}");
// 4. The delta reconstructs exactly what the next full request answers.
let delta = messages.iter().find(|m| m["id"] == 4).expect("delta response");
assert!(delta["result"].get("edits").is_some(), "a known id gets edits: {delta:#?}");
let truth = messages.iter().find(|m| m["id"] == 5).expect("second full response");
assert_eq!(
apply_token_edits(&held, &delta["result"]),
token_numbers(&truth["result"]["data"]),
"applying the edits must land on the new token set exactly"
);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn indexing_reports_its_progress_over_the_wire() {
// What only an e2e test can check: the create request and the two
// `$/progress` notifications are framed, ordered, and carry the same
// token — for a client that advertised `window.workDoneProgress`.
let dir = temp_dir("progress");
let file = dir.join("m.sv");
let source = "module m;\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":{{"window":{{"workDoneProgress":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(source).expect("json")
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didSave","params":{{"textDocument":{{"uri":"{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);
// Every progress message on the wire, in order, as (step, token).
let steps: Vec<(String, String)> = messages
.iter()
.filter_map(|m| match m["method"].as_str() {
Some("window/workDoneProgress/create") => Some((
"create".to_string(),
m["params"]["token"].as_str().expect("a string token").to_string(),
)),
Some("$/progress") => Some((
m["params"]["value"]["kind"].as_str().expect("a kind").to_string(),
m["params"]["token"].as_str().expect("a string token").to_string(),
)),
_ => None,
})
.collect();
// **Two** rescans, and the shape of them is the folder scope on the wire
// (index-scope, 2026-08-27) plus the incremental save path
// (incremental-index, 2026-08-27). The startup build has **no file to
// scan** — the default scope is the open buffers' folders and no buffer is
// open yet — so its bar carries no report; the `didOpen` widens the scope
// to `m.sv`'s folder and rebuilds, reporting the one file. The **save
// puts no bar up at all**: it names one file the index already holds, so
// it is one parse on the incremental path rather than a scan to report.
assert_eq!(
steps,
vec![
("create".to_string(), "lucisv-index-0".to_string()),
("begin".to_string(), "lucisv-index-0".to_string()),
("end".to_string(), "lucisv-index-0".to_string()),
("create".to_string(), "lucisv-index-1".to_string()),
("begin".to_string(), "lucisv-index-1".to_string()),
("report".to_string(), "lucisv-index-1".to_string()),
("end".to_string(), "lucisv-index-1".to_string()),
],
"{messages:#?}"
);
// The report counts, on the wire: "1/1 m.sv" at 100%.
let report =
messages.iter().find(|m| m["params"]["value"]["kind"] == "report").expect("a report");
assert_eq!(report["params"]["value"]["message"], "1/1 m.sv", "{report:#?}");
assert_eq!(report["params"]["value"]["percentage"], 100, "{report:#?}");
// The begin says what it is doing, and offers no cancel button — a rescan
// that has started runs to completion, whatever `$/cancelRequest` can do
// for the requests still queued.
let begin = messages.iter().find(|m| m["params"]["value"]["kind"] == "begin").expect("a begin");
assert_eq!(begin["params"]["value"]["title"], "Indexing Verilog workspace", "{begin:#?}");
assert_eq!(begin["params"]["value"]["cancellable"], false, "{begin:#?}");
assert!(begin["params"]["value"].get("percentage").is_none(), "no fake numbers: {begin:#?}");
// The startup bar ends at nothing indexed — honestly, since the folder
// scope had no folder yet — and the `didOpen` rebuild after it names the
// file. The save has no bar to end.
let ends: Vec<&serde_json::Value> = messages
.iter()
.filter(|m| m["params"]["value"]["kind"] == "end")
.map(|m| &m["params"]["value"]["message"])
.collect();
assert_eq!(ends, ["0 files indexed", "1 file indexed"], "{messages:#?}");
// The create is a request the client may answer or error; leaving it
// unanswered here is exactly what a client that does not care does, and
// the session still shuts down cleanly (asserted inside `talk`).
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn the_size_cap_and_the_file_log_work_over_the_wire() {
// The three settings of `docs/features/indexing-ux/README.md` together,
// against the real binary: a pushed cap rescans, the oversized file is
// gone from the index, the log names every file and the skip, and the bar
// counts what is left.
let dir = temp_dir("indexcap");
std::fs::write(dir.join("keep.sv"), "package keep_pkg;\n localparam K = 1;\nendpackage\n")
.expect("write");
let mut fat = String::from("package netlist_pkg;\n localparam K = 1;\nendpackage\n// ");
while fat.len() < 4096 {
fat.push('x');
}
fat.push('\n');
std::fs::write(dir.join("netlist.sv"), &fat).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":{{"window":{{"workDoneProgress":true}}}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
// The cap arrives the way VS Code sends a dotted setting: nested. It
// carries `scope: "workspace"` because this test is about the cap, and
// a push replaces every setting — without it the same message would
// narrow the index to the folder scope in the same breath.
frame(
r#"{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{"settings":{"lucisv":{"index":{"maxFileSize":1024,"scope":"workspace"}}}}}"#,
),
frame(
r#"{"jsonrpc":"2.0","id":2,"method":"workspace/symbol","params":{"query":"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);
// 1. The capped file is not in the index; the other one is.
let symbols = messages.iter().find(|m| m["id"] == 2).expect("symbol response");
let names: Vec<&str> = symbols["result"]
.as_array()
.expect("an array")
.iter()
.filter_map(|s| s["name"].as_str())
.collect();
assert!(names.contains(&"keep_pkg"), "{symbols:#?}");
assert!(!names.contains(&"netlist_pkg"), "the capped file is invisible: {symbols:#?}");
// 2. The log named every file it read, and the one it did not.
let logged: Vec<&str> = messages
.iter()
.filter(|m| m["method"] == "window/logMessage")
.filter_map(|m| m["params"]["message"].as_str())
.collect();
assert!(
messages
.iter()
.filter(|m| m["method"] == "window/logMessage")
.all(|m| m["params"]["type"] == 4),
"MessageType::LOG, which vscode-languageclient appends verbatim: {logged:?}"
);
assert!(
logged.iter().any(|l| l.starts_with("indexing: ") && l.ends_with("keep.sv")),
"{logged:?}"
);
let skip = logged
.iter()
.find(|l| l.starts_with("skipped ("))
.unwrap_or_else(|| panic!("a skip line: {logged:?}"));
assert!(skip.ends_with("netlist.sv"), "{skip}");
assert!(skip.starts_with("skipped (4.0 KiB > 1.0 KiB cap): "), "{skip}");
// 3. The bar for the rescan the cap triggered: one file of one, and an
// end that counts the skip.
let after: Vec<&serde_json::Value> = messages
.iter()
.filter(|m| m["method"] == "$/progress" && m["params"]["token"] == "lucisv-index-1")
.collect();
let kinds: Vec<&str> =
after.iter().filter_map(|m| m["params"]["value"]["kind"].as_str()).collect();
assert_eq!(kinds, ["begin", "report", "end"], "the cap change rescanned: {after:#?}");
assert_eq!(after[1]["params"]["value"]["message"], "1/1 keep.sv", "{after:#?}");
assert_eq!(after[1]["params"]["value"]["percentage"], 100, "{after:#?}");
assert_eq!(after[2]["params"]["value"]["message"], "1 file indexed, 1 skipped", "{after:#?}");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn qa_the_analyzed_log_word_names_only_the_open_buffer_and_only_on_a_rescan() {
// QA attack (index-scope, 2026-08-28, charter item 5). No e2e test
// exercised the real `analyzed: <path>` log line at all before this one —
// `state.rs`'s unit tests only ever check the `IndexEvent::Analyzed`
// variant, never the formatted string a real client would see over
// `window/logMessage`. Two claims: the widening `didOpen`'s rescan logs
// `analyzed:` for the open buffer and `indexing:` (never `analyzed:`) for
// the file that is only ever on disk; and the follow-up `didSave` — the
// incremental one-file path — sends no log line at all, so `analyzed:`
// cannot leak onto a request that was never a scan.
let dir = temp_dir("analyzedword");
std::fs::write(
dir.join("disk_only.sv"),
"package disk_pkg;\n localparam K = 1;\nendpackage\n",
)
.expect("write");
let file = dir.join("m.sv");
let source = "module m;\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":{{"window":{{"workDoneProgress":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(source).expect("json")
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didSave","params":{{"textDocument":{{"uri":"{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 logged: Vec<&str> = messages
.iter()
.filter(|m| m["method"] == "window/logMessage")
.filter_map(|m| m["params"]["message"].as_str())
.collect();
// The `didOpen` rescan: the open buffer's own analysis, the disk file
// parsed.
assert!(
logged.iter().any(|l| l.starts_with("analyzed: ") && l.ends_with("m.sv")),
"the open buffer must be logged `analyzed:`: {logged:?}"
);
assert!(
logged.iter().any(|l| l.starts_with("indexing: ") && l.ends_with("disk_only.sv")),
"the disk-only file must still be logged `indexing:`: {logged:?}"
);
assert!(
!logged.iter().any(|l| l.starts_with("analyzed: ") && l.ends_with("disk_only.sv")),
"a file with no open buffer is never `analyzed:`: {logged:?}"
);
assert!(
!logged.iter().any(|l| l.starts_with("indexing: ") && l.ends_with("m.sv")),
"the open buffer is not reparsed, so it is never `indexing:`: {logged:?}"
);
// The `didSave` afterwards names one file the index already holds, so it
// takes the incremental `reindex_one` path — which the work log states
// sends no per-file log line at all. Confirmed here rather than assumed:
// there is exactly one `didOpen`-rescan's worth of log lines and nothing
// from the save.
assert_eq!(
logged
.iter()
.filter(|l| l.starts_with("analyzed: ") || l.starts_with("indexing: "))
.count(),
2,
"one line for each of the two files, from the rescan alone: {logged:?}"
);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_client_that_never_asked_for_progress_is_sent_none_over_the_wire() {
let dir = temp_dir("noprogress");
let file = dir.join("m.sv");
let source = "module m;\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")
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didSave","params":{{"textDocument":{{"uri":"{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);
assert!(
messages.iter().all(|m| {
m["method"] != "$/progress" && m["method"] != "window/workDoneProgress/create"
}),
"the spec forbids progress a client never asked for: {messages:#?}"
);
// And it still got its diagnostics, so the save path ran.
assert!(
messages.iter().any(|m| m["method"] == "textDocument/publishDiagnostics"),
"{messages:#?}"
);
let _ = std::fs::remove_dir_all(&dir);
}
/// The ids the flood cancels — every second request.
fn is_cancelled(id: u32) -> bool {
id % 2 == 1
}
#[test]
fn a_flood_of_requests_and_cancels_is_answered_exactly_once_each() {
// The one test that runs the real `run()` loop, and so the only one that
// exercises the burst drain over a real pipe. The whole session is written
// in a single `write` before a byte is read back, so every request and the
// cancel behind it are in flight together — which is the only situation a
// one-message-at-a-time server can honour a cancel in at all.
//
// **How many get cancelled is not asserted, and cannot be.** Whether a
// cancel reaches the loop in the same burst as its request is a race with
// the transport's own threads, and the spec's answer to losing it is to
// answer the request normally. So this pins what must hold either way —
// one answer per request, never a wrong one — plus the fact that the
// cancellation path does work over the wire. Twenty formatting requests
// over a three-hundred-line buffer is enough work per message that the
// backlog is real: under a twenty-four-way overload the worst observed
// was two in five honoured, never none.
let dir = temp_dir("cancelflood");
let file = dir.join("m.sv");
let source: String = std::iter::once("module flooded;\n".to_string())
.chain((0..300).map(|i| format!("wire w{i};\n")))
.chain(std::iter::once("endmodule\n".to_string()))
.collect();
std::fs::write(&file, &source).expect("write");
let root = format!("file://{}", dir.display());
let uri = format!("file://{}", file.display());
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 10..30u32 {
session.push(frame(&format!(
r#"{{"jsonrpc":"2.0","id":{id},"method":"textDocument/formatting","params":{{"textDocument":{{"uri":"{uri}"}},"options":{{"tabSize":2,"insertSpaces":true}}}}}}"#
)));
if is_cancelled(id) {
session.push(frame(&format!(
r#"{{"jsonrpc":"2.0","method":"$/cancelRequest","params":{{"id":{id}}}}}"#
)));
}
}
// A cancel for a request this server was never sent. It names nothing in
// any burst, so it is dropped where it is read.
session.push(frame(r#"{"jsonrpc":"2.0","method":"$/cancelRequest","params":{"id":999}}"#));
session.push(frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#));
session.push(frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#));
let messages = talk(&session.concat());
let mut honoured = 0;
for id in 10..30u32 {
let answers: Vec<&serde_json::Value> = messages.iter().filter(|m| m["id"] == id).collect();
assert_eq!(answers.len(), 1, "id {id} was answered exactly once: {messages:#?}");
let answer = answers[0];
if answer.get("error").is_some() {
assert!(is_cancelled(id), "id {id} was never cancelled: {answer:#?}");
assert_eq!(answer["error"]["code"], -32800, "cancelled, not failed: {answer:#?}");
assert!(answer.get("result").is_none(), "an error carries no result: {answer:#?}");
assert!(
answer["error"]["message"].as_str().is_some_and(|m| !m.is_empty()),
"a cancelled response carries a message: {answer:#?}"
);
honoured += 1;
} else {
// Answered for real: the whole buffer, indented.
let edits = answer["result"].as_array().expect("an array of edits");
assert_eq!(edits.len(), 1, "one whole-document edit: {answer:#?}");
assert!(
edits[0]["newText"]
.as_str()
.expect("newText")
.starts_with("module flooded;\n wire w0;\n"),
"id {id} was formatted: {answer:#?}"
);
}
}
assert!(honoured > 0, "the cancellation path runs over the wire: {messages:#?}");
// The shutdown came through the same flood and was still honoured —
// `talk` asserts the process then exited cleanly.
let shutdown = messages.iter().find(|m| m["id"] == 9).expect("a shutdown response");
assert!(shutdown.get("error").is_none(), "shutdown succeeded: {shutdown:#?}");
let _ = std::fs::remove_dir_all(&dir);
}
/// The same flood, `--verbose` this time: the timing notify shares the
/// writer channel with every response, so this is where a reordering or an
/// interleaving in the byte stream would show up first.
///
/// **What a cancelled request's timing line looks like: none.** `request`
/// (the timing wrapper) is never reached for an id `process_batch` already
/// answered from the cancelled set — cancellation is resolved before
/// `self.request(request)` is called — so a cancelled id contributes no
/// `answered in` line at all. That is deliberate (there is nothing to time:
/// the handler never ran) and this test is what pins it, since neither the
/// feature README nor `tests/e2e.rs` said so before this round's QA pass
/// (`docs/features/verbose-timing/README.md`, QA log 2026-08-29).
#[test]
fn a_flood_of_requests_and_cancels_under_verbose_times_only_what_ran_and_corrupts_nothing() {
let dir = temp_dir("cancelflood_verbose");
let file = dir.join("m.sv");
let source: String = std::iter::once("module flooded;\n".to_string())
.chain((0..300).map(|i| format!("wire w{i};\n")))
.chain(std::iter::once("endmodule\n".to_string()))
.collect();
std::fs::write(&file, &source).expect("write");
let root = format!("file://{}", dir.display());
let uri = format!("file://{}", file.display());
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 10..30u32 {
session.push(frame(&format!(
r#"{{"jsonrpc":"2.0","id":{id},"method":"textDocument/formatting","params":{{"textDocument":{{"uri":"{uri}"}},"options":{{"tabSize":2,"insertSpaces":true}}}}}}"#
)));
if is_cancelled(id) {
session.push(frame(&format!(
r#"{{"jsonrpc":"2.0","method":"$/cancelRequest","params":{{"id":{id}}}}}"#
)));
}
}
session.push(frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#));
session.push(frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#));
let messages = talk_with(&["--verbose"], &session.concat());
// Every id still answered exactly once — a corrupted or reordered byte
// stream would show up here first, as a missing or duplicated answer.
let mut honoured = 0;
for id in 10..30u32 {
let answers: Vec<&serde_json::Value> = messages.iter().filter(|m| m["id"] == id).collect();
assert_eq!(answers.len(), 1, "id {id} was answered exactly once: {messages:#?}");
if answers[0].get("error").is_some() {
honoured += 1;
}
}
let shutdown = messages.iter().find(|m| m["id"] == 9).expect("a shutdown response");
assert!(shutdown.get("error").is_none(), "shutdown succeeded: {messages:#?}");
// And the timing lines agree with what actually ran: one
// `textDocument/formatting answered in` line per request that was NOT
// served from the cancelled set — never one for a cancelled id, which
// never reaches the timed wrapper at all.
let lines = timing_lines(&messages);
let answered_formatting = lines
.iter()
.filter(|l| l.starts_with("timing: textDocument/formatting answered in"))
.count();
let not_cancelled = 20 - honoured;
assert_eq!(
answered_formatting, not_cancelled,
"one timing line per request the handler actually ran, none for a cancelled one: {lines:#?}"
);
let _ = std::fs::remove_dir_all(&dir);
}
const TYPEDEF_PKG: &str = "\
package e2e_tdp;
typedef enum logic [1:0] { IDLE, RUN } state_t;
endpackage
";
const TYPEDEF_TOP: &str = "\
module e2e_tdtop;
e2e_tdp::state_t s;
endmodule
";
#[test]
fn a_type_definition_crosses_a_file_over_the_wire() {
// What only an e2e test can check: that the capability is advertised in
// the real handshake and that the request is dispatched at all. The
// answer itself — a package's typedef, reached from a variable in
// another file — is the cross-file half of the feature.
let dir = temp_dir("typedef");
let pkg = dir.join("e2e_tdp.sv");
std::fs::write(&pkg, TYPEDEF_PKG).expect("write");
let top = dir.join("e2e_tdtop.sv");
std::fs::write(&top, TYPEDEF_TOP).expect("write");
let root = format!("file://{}", dir.display());
let uri = format!("file://{}", top.display());
let pkg_uri = format!("file://{}", pkg.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(TYPEDEF_TOP).expect("json")
)),
// The cursor on `s`, whose type is declared in the package.
frame(&format!(
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/typeDefinition","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":1,"character":19}}}}}}"#
)),
// And on `logic`, a built-in, which has no declaration to jump to.
frame(&format!(
r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/typeDefinition","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":0,"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["typeDefinitionProvider"], true, "{capabilities:#?}");
let locations = response(2)["result"].as_array().expect("a location list");
assert_eq!(locations.len(), 1, "{locations:#?}");
assert_eq!(locations[0]["uri"], pkg_uri.as_str(), "the package's own file");
assert_eq!(locations[0]["range"]["start"]["line"], 1);
assert_eq!(locations[0]["range"]["start"]["character"], 41, "the typedef's name");
let nothing = response(3)["result"].as_array().expect("an empty list, not null");
assert!(nothing.is_empty(), "{nothing:#?}");
let _ = std::fs::remove_dir_all(&dir);
}
/// A module and a named block, each closing with the label it repeats — the
/// two shapes linked editing exists for.
const LINKED_SRC: &str = "\
module e2e_link;
initial begin : blk
end : blk
endmodule : e2e_link
";
#[test]
fn a_linked_editing_range_round_trips_over_the_wire() {
// What only an e2e test can check: that the capability reaches a real
// handshake, that the request is dispatched, and that both the ranges and
// the optional `wordPattern` survive serialization.
let dir = temp_dir("linked");
let file = dir.join("e2e_link.sv");
std::fs::write(&file, LINKED_SRC).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(LINKED_SRC).expect("json")
)),
// The cursor inside the `endmodule : e2e_link` label — the far half of
// the pair, so the answer has to reach back to line 0.
frame(&format!(
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/linkedEditingRange","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":3,"character":15}}}}}}"#
)),
// The cursor on the named block's own label, one line up.
frame(&format!(
r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/linkedEditingRange","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":2,"character":8}}}}}}"#
)),
// And on the `initial` keyword, which is on no name at all.
frame(&format!(
r#"{{"jsonrpc":"2.0","id":4,"method":"textDocument/linkedEditingRange","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":1,"character":2}}}}}}"#
)),
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["linkedEditingRangeProvider"], true, "{capabilities:#?}");
let module = &response(2)["result"];
let ranges = module["ranges"].as_array().expect("a range list");
assert_eq!(ranges.len(), 2, "{module:#?}");
assert_eq!(ranges[0]["start"]["line"], 0);
assert_eq!(ranges[0]["start"]["character"], 7, "the header name");
assert_eq!(ranges[0]["end"]["character"], 15);
assert_eq!(ranges[1]["start"]["line"], 3);
assert_eq!(ranges[1]["start"]["character"], 12, "the endmodule label");
assert_eq!(ranges[1]["end"]["character"], 20);
assert_eq!(
module["wordPattern"], "^[A-Za-z_][A-Za-z0-9_$]*$",
"the SV identifier pattern, sent so a client does not fall back to one without `$`"
);
let block = &response(3)["result"];
let ranges = block["ranges"].as_array().expect("a range list");
assert_eq!(ranges.len(), 2, "{block:#?}");
assert_eq!(ranges[0]["start"]["line"], 1, "the `begin : blk` label");
assert_eq!(ranges[1]["start"]["line"], 2, "the `end : blk` label");
assert!(response(4)["result"].is_null(), "a keyword links nothing: {:#?}", response(4));
let _ = std::fs::remove_dir_all(&dir);
}
const LENS_SUB: &str = "module lens_sub (input logic clk);\nendmodule\n";
const LENS_TOP: &str = "\
module lens_top;
lens_sub u_a (.clk(1'b0));
lens_sub u_b (.clk(1'b1));
endmodule
";
#[test]
fn code_lenses_and_their_command_round_trip_over_the_wire() {
// What only an e2e test can check: that the capability reaches a real
// handshake in the shape a client reads, that the lens is dispatched, and
// that the command a lens carries is one `workspace/executeCommand`
// actually runs — the two halves are declared in different places and
// could drift apart without ever failing to compile.
let dir = temp_dir("codelens");
let sub = dir.join("lens_sub.sv");
std::fs::write(&sub, LENS_SUB).expect("write");
let top = dir.join("lens_top.sv");
std::fs::write(&top, LENS_TOP).expect("write");
let root = format!("file://{}", dir.display());
let uri = format!("file://{}", sub.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":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string(LENS_SUB).expect("json")
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/codeLens","params":{{"textDocument":{{"uri":"{uri}"}}}}}}"#
)),
frame(
r#"{"jsonrpc":"2.0","id":3,"method":"workspace/executeCommand","params":{"command":"lucisv.showInstantiations","arguments":["lens_sub"]}}"#,
),
// A buffer the server was never sent answers `null`, not an empty list.
frame(&format!(
r#"{{"jsonrpc":"2.0","id":4,"method":"textDocument/codeLens","params":{{"textDocument":{{"uri":"{top_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 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["codeLensProvider"],
serde_json::json!({ "resolveProvider": false }),
"{capabilities:#?}"
);
let commands =
capabilities["executeCommandProvider"]["commands"].as_array().expect("the command list");
assert!(
commands.contains(&serde_json::json!("lucisv.showInstantiations")),
"the lens's command has to be advertised to be runnable: {commands:#?}"
);
let lenses = response(2)["result"].as_array().expect("a lens list");
assert_eq!(lenses.len(), 1, "{lenses:#?}");
assert_eq!(lenses[0]["command"]["title"], "2 instantiations");
assert_eq!(lenses[0]["command"]["command"], "lucisv.showInstantiations");
assert_eq!(lenses[0]["command"]["arguments"], serde_json::json!(["lens_sub"]));
assert_eq!(
lenses[0]["range"],
serde_json::json!({
"start": { "line": 0, "character": 7 }, "end": { "line": 0, "character": 15 }
}),
"the declaration's own name, so the lens draws above the header"
);
assert!(lenses[0].get("data").is_none(), "nothing left for a resolve: {:#?}", lenses[0]);
let sites = response(3)["result"].as_array().expect("a location list");
assert_eq!(sites.len(), 2, "the count the lens showed, as places: {sites:#?}");
assert_eq!(sites[0]["uri"], top_uri.as_str());
assert_eq!(sites[0]["range"]["start"], serde_json::json!({ "line": 1, "character": 2 }));
assert_eq!(sites[1]["range"]["start"], serde_json::json!({ "line": 2, "character": 2 }));
assert!(response(4)["result"].is_null(), "an unopened buffer: {:#?}", response(4));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_save_asks_a_capable_client_to_refresh_its_code_lenses_over_the_wire() {
// A rescan can change any count on screen, so a client holding lenses has
// to be told to ask again — and only a client that said it can be.
let dir = temp_dir("codelensrefresh");
let sub = dir.join("lens_sub.sv");
std::fs::write(&sub, LENS_SUB).expect("write");
std::fs::write(dir.join("lens_top.sv"), LENS_TOP).expect("write");
let root = format!("file://{}", dir.display());
let uri = format!("file://{}", sub.display());
let script = |capabilities: &str| {
[
frame(&format!(
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{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(LENS_SUB).expect("json")
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didSave","params":{{"textDocument":{{"uri":"{uri}"}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
]
.concat()
};
let refreshes = |messages: &[serde_json::Value]| -> usize {
messages.iter().filter(|m| m["method"] == "workspace/codeLens/refresh").count()
};
// One per rescan, and this script has two: the `didOpen` widens the folder
// scope to `lens_sub.sv`'s own folder and rebuilds (index-scope,
// 2026-08-27), and then the save rebuilds again.
let capable = talk(&script(r#"{"workspace":{"codeLens":{"refreshSupport":true}}}"#));
assert_eq!(refreshes(&capable), 2, "one per rescan: {capable:#?}");
let silent = talk(&script("{}"));
assert_eq!(refreshes(&silent), 0, "a client that did not ask is never told: {silent:#?}");
let _ = std::fs::remove_dir_all(&dir);
}
const TYPE_BASE: &str = "class type_base;\n int x;\nendclass\n";
const TYPE_MID: &str = "class type_mid extends type_base;\n int y;\nendclass\n";
const TYPE_LEAF: &str = "class type_leaf extends type_mid;\nendclass\n";
#[test]
fn the_class_hierarchy_round_trips_over_the_wire_in_both_directions() {
// What only an e2e test can check: that `typeHierarchyProvider` is
// advertised in the shape a client reads — `lsp-types` has no field for it,
// so it is written into the serialized capabilities by hand — 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("type_hierarchy");
let base = dir.join("type_base.sv");
std::fs::write(&base, TYPE_BASE).expect("write");
let mid = dir.join("type_mid.sv");
std::fs::write(&mid, TYPE_MID).expect("write");
let leaf = dir.join("type_leaf.sv");
std::fs::write(&leaf, TYPE_LEAF).expect("write");
let root = format!("file://{}", dir.display());
let mid_uri = format!("file://{}", mid.display());
let base_uri = format!("file://{}", base.display());
let leaf_uri = format!("file://{}", leaf.display());
// The item a client holds after `prepareTypeHierarchy` and sends back for
// each direction: `type_mid`, declared on lines 0..2 of `type_mid.sv`.
let mid_item = format!(
r#"{{"name":"type_mid","kind":5,"uri":"{mid_uri}","range":{{"start":{{"line":0,"character":0}},"end":{{"line":2,"character":8}}}},"selectionRange":{{"start":{{"line":0,"character":6}},"end":{{"line":0,"character":14}}}}}}"#
);
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(TYPE_MID).expect("json")
)),
// The cursor on the `type_mid` of its own declaration.
frame(&format!(
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/prepareTypeHierarchy","params":{{"textDocument":{{"uri":"{mid_uri}"}},"position":{{"line":0,"character":8}}}}}}"#
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":3,"method":"typeHierarchy/supertypes","params":{{"item":{mid_item}}}}}"#
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":4,"method":"typeHierarchy/subtypes","params":{{"item":{mid_item}}}}}"#
)),
// A property name is not a class, so there is no hierarchy to open.
frame(&format!(
r#"{{"jsonrpc":"2.0","id":5,"method":"textDocument/prepareTypeHierarchy","params":{{"textDocument":{{"uri":"{mid_uri}"}},"position":{{"line":1,"character":7}}}}}}"#
)),
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["typeHierarchyProvider"], 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::<serde_json::Value>(&mid_item).expect("json"),
"the item the client will send back is exactly the one built here"
);
let supertypes = response(3)["result"].as_array().expect("a list of items");
assert_eq!(supertypes.len(), 1, "one base: {supertypes:#?}");
assert_eq!(supertypes[0]["name"], "type_base");
assert_eq!(supertypes[0]["uri"], base_uri.as_str());
assert_eq!(supertypes[0]["kind"], 5, "SymbolKind.Class");
assert_eq!(
supertypes[0]["selectionRange"],
serde_json::json!({
"start": { "line": 0, "character": 6 }, "end": { "line": 0, "character": 15 }
}),
"the base's own name span, in its own file"
);
let subtypes = response(4)["result"].as_array().expect("a list of items");
assert_eq!(subtypes.len(), 1, "one subtype: {subtypes:#?}");
assert_eq!(subtypes[0]["name"], "type_leaf");
assert_eq!(subtypes[0]["uri"], leaf_uri.as_str());
assert_eq!(subtypes[0]["kind"], 5, "SymbolKind.Class");
assert_eq!(response(5)["result"], serde_json::Value::Null, "a property name is no class");
let _ = std::fs::remove_dir_all(&dir);
}
/// One `TextEdit` applied the way a client applies it: by line and character.
/// The fixtures below are ASCII, so a UTF-16 character is a byte column.
fn apply_edits(text: &str, edits: &[serde_json::Value]) -> String {
let mut lines: Vec<String> = text.split('\n').map(str::to_string).collect();
for edit in edits {
let range = &edit["range"];
let line = range["start"]["line"].as_u64().expect("line") as usize;
assert_eq!(range["end"]["line"], range["start"]["line"], "one line per edit: {edit:#?}");
let (from, to) = (
range["start"]["character"].as_u64().expect("start") as usize,
range["end"]["character"].as_u64().expect("end") as usize,
);
let new_text = edit["newText"].as_str().expect("newText");
lines[line].replace_range(from..to, new_text);
}
lines.join("\n")
}
/// The file-operations round trip against the real binary: the server is asked
/// what a rename costs, the answer is applied and the rename performed exactly
/// as a client would, and a second session proves the include resolves again
/// at its new location — the whole point of the exercise.
#[test]
fn a_rename_round_trips_through_the_edit_and_leaves_the_include_resolving() {
let dir = temp_dir("willrename");
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");
let source = "`include \"inc/defs.svh\"\nmodule top;\nendmodule\n";
std::fs::write(&top, source).expect("write");
let root = format!("file://{}", dir.display());
let top_uri = format!("file://{}", top.display());
let old_uri = format!("file://{}", defs.display());
let moved = dir.join("inc/widths.svh");
let new_uri = format!("file://{}", moved.display());
// Session one: "I am about to rename inc/defs.svh to inc/widths.svh."
let messages = talk(
&[
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(WIDE_SCOPE),
frame(WIDE_SCOPE),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":2,"method":"workspace/willRenameFiles","params":{{"files":[{{"oldUri":"{old_uri}","newUri":"{new_uri}"}}]}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
]
.concat(),
);
// The capability is advertised where a client looks for it.
let initialized = messages.iter().find(|m| m["id"] == 1).expect("initialize response");
let operations = &initialized["result"]["capabilities"]["workspace"]["fileOperations"];
assert!(operations["willRename"]["filters"].is_array(), "{initialized:#?}");
let answer = messages.iter().find(|m| m["id"] == 2).expect("willRename response");
let edits = answer["result"]["changes"][&top_uri].as_array().expect("edits for top.sv");
assert_eq!(edits.len(), 1, "{answer:#?}");
// The client's half: apply the edit, then do the rename.
let rewritten = apply_edits(source, edits);
assert_eq!(rewritten, "`include \"inc/widths.svh\"\nmodule top;\nendmodule\n");
std::fs::write(&top, &rewritten).expect("write back");
std::fs::rename(&defs, &moved).expect("rename");
// Session two: the include is a live link again, at the new path.
let messages = talk(
&[
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(WIDE_SCOPE),
frame(WIDE_SCOPE),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"workspace/didRenameFiles","params":{{"files":[{{"oldUri":"{old_uri}","newUri":"{new_uri}"}}]}}}}"#
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{top_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string(&rewritten).expect("json")
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/documentLink","params":{{"textDocument":{{"uri":"{top_uri}"}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
]
.concat(),
);
let links = messages.iter().find(|m| m["id"] == 2).expect("documentLink response")["result"]
.as_array()
.expect("a link list")
.clone();
assert_eq!(links.len(), 1, "{links:#?}");
assert_eq!(links[0]["target"], new_uri.as_str(), "the include resolves to the new file");
let _ = std::fs::remove_dir_all(&dir);
}
/// The mirror case, at the wire: the file *being renamed* is also the one
/// whose own include needs rewriting (its own-directory rung moves with it).
/// Per LSP, `willRenameFiles` edits apply before the rename, so the
/// `WorkspaceEdit` must name the file's *old* URI — a `TextDocumentEdit`
/// naming the new URI would be silently dropped by a real client, since that
/// document does not exist yet at the time the edit is applied. This is the
/// highest-risk detail in the feature, so it is pinned at the JSON-RPC level,
/// not just through the handler.
#[test]
fn a_moving_includer_s_own_edit_is_addressed_to_its_old_uri_on_the_wire() {
let dir = temp_dir("willrenameself");
std::fs::create_dir_all(dir.join("rtl")).expect("rtl");
std::fs::create_dir_all(dir.join("src")).expect("src");
std::fs::write(dir.join("rtl/defs.svh"), "`define WIDTH 8\n").expect("write");
let old_top = dir.join("rtl/top.sv");
std::fs::write(&old_top, "`include \"defs.svh\"\nmodule top;\nendmodule\n").expect("write");
let new_top = dir.join("src/top.sv");
let root = format!("file://{}", dir.display());
let old_uri = format!("file://{}", old_top.display());
let new_uri = format!("file://{}", new_top.display());
let messages = talk(
&[
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(WIDE_SCOPE),
frame(WIDE_SCOPE),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":2,"method":"workspace/willRenameFiles","params":{{"files":[{{"oldUri":"{old_uri}","newUri":"{new_uri}"}}]}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
]
.concat(),
);
let answer = messages.iter().find(|m| m["id"] == 2).expect("willRename response");
let changes = answer["result"]["changes"].as_object().expect("changes map");
assert_eq!(changes.len(), 1, "{answer:#?}");
assert!(
changes.contains_key(&old_uri),
"the edit must be addressed to the pre-rename URI: {answer:#?}"
);
assert!(
!changes.contains_key(&new_uri),
"a client applies these edits before the rename — the new URI does not \
exist yet and an edit there would be dropped: {answer:#?}"
);
let edits = changes[&old_uri].as_array().expect("edits");
assert_eq!(edits[0]["newText"], serde_json::json!("../rtl/defs.svh"), "{answer:#?}");
let _ = std::fs::remove_dir_all(&dir);
}
/// §9c (folders-and-config): a folder added mid-session, over the real wire.
///
/// What only an e2e test can settle: that the two halves of
/// `workspace.workspaceFolders` reach a real handshake at the key a client
/// reads (without `changeNotifications` no editor ever sends the
/// notification, however well it is handled), and that a cross-file jump into
/// a folder the server did not have at `initialize` resolves afterwards.
#[test]
fn a_folder_added_mid_session_is_indexed_over_the_wire() {
let first = temp_dir("foldersfirst");
let second = temp_dir("folderssecond");
// `top.sv` uses a parameter the *second* folder's package declares, so
// the jump can only resolve once that folder is part of the workspace.
let top = first.join("top.sv");
std::fs::write(&top, "module top;\n localparam W = added_pkg::WIDTH;\nendmodule\n")
.expect("write");
let added = second.join("added_pkg.sv");
std::fs::write(&added, "package added_pkg;\n localparam WIDTH = 8;\nendpackage\n")
.expect("write");
let first_uri = format!("file://{}", first.display());
let second_uri = format!("file://{}", second.display());
let top_uri = format!("file://{}", top.display());
let added_uri = format!("file://{}", added.display());
// The cursor on `WIDTH` in `added_pkg::WIDTH`.
let definition = |id: u32| {
format!(
r#"{{"jsonrpc":"2.0","id":{id},"method":"textDocument/definition","params":{{"textDocument":{{"uri":"{top_uri}"}},"position":{{"line":1,"character":30}}}}}}"#
)
};
let mut live = Live::start();
live.send(&format!(
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"workspaceFolders":[{{"uri":"{first_uri}","name":"first"}}],"capabilities":{{"workspace":{{"workspaceFolders":true}}}}}}}}"#
));
let handshake = live.wait_for(|m| m["id"] == 1);
assert_eq!(
handshake["result"]["capabilities"]["workspace"]["workspaceFolders"],
serde_json::json!({ "supported": true, "changeNotifications": true }),
"{handshake:#?}"
);
live.send(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#);
live.send(WIDE_SCOPE);
live.send(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{top_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string("module top;\n localparam W = added_pkg::WIDTH;\nendmodule\n")
.expect("json")
));
live.send(&definition(2));
let before = live.wait_for(|m| m["id"] == 2);
assert_eq!(
before["result"].as_array().map(Vec::len),
Some(0),
"premise: the second folder is not in the workspace yet: {before:#?}"
);
// "Add Folder to Workspace".
live.send(&format!(
r#"{{"jsonrpc":"2.0","method":"workspace/didChangeWorkspaceFolders","params":{{"event":{{"added":[{{"uri":"{second_uri}","name":"second"}}],"removed":[]}}}}}}"#
));
live.send(&definition(3));
let after = live.wait_for(|m| m["id"] == 3);
let targets = after["result"].as_array().expect("a location list");
assert_eq!(targets.len(), 1, "{after:#?}");
assert_eq!(targets[0]["uri"], added_uri.as_str(), "{after:#?}");
// ...and closing it again takes those answers away.
live.send(&format!(
r#"{{"jsonrpc":"2.0","method":"workspace/didChangeWorkspaceFolders","params":{{"event":{{"added":[],"removed":[{{"uri":"{second_uri}","name":"second"}}]}}}}}}"#
));
live.send(&definition(4));
let gone = live.wait_for(|m| m["id"] == 4);
assert_eq!(gone["result"].as_array().map(Vec::len), Some(0), "{gone:#?}");
live.finish();
let _ = std::fs::remove_dir_all(&first);
let _ = std::fs::remove_dir_all(&second);
}
/// §9c (folders-and-config): the server-pull settings round trip.
///
/// The push half is covered by `pushed_settings_reach_the_formatter...`; this
/// is the pull half, and only a live session can drive it — the server asks,
/// the test answers as a client would, and the very next format shows the
/// answer took.
#[test]
fn the_configuration_pull_round_trips_over_the_wire() {
let dir = temp_dir("configpull");
let file = dir.join("pull_me.sv");
std::fs::write(&file, "module pull_me;\nwire a;\nendmodule\n").expect("write");
let root = format!("file://{}", dir.display());
let uri = format!("file://{}", file.display());
let format = |id: u32| {
format!(
r#"{{"jsonrpc":"2.0","id":{id},"method":"textDocument/formatting","params":{{"textDocument":{{"uri":"{uri}"}},"options":{{"tabSize":2,"insertSpaces":true}}}}}}"#
)
};
let mut live = Live::start();
live.send(&format!(
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{"workspace":{{"configuration":true}}}}}}}}"#
));
live.wait_for(|m| m["id"] == 1);
live.send(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#);
// The server asks, unprompted, exactly once and for exactly our section.
let pull = live.wait_for(|m| m["method"] == "workspace/configuration");
assert_eq!(
pull["params"],
serde_json::json!({ "items": [{ "section": "lucisv" }] }),
"{pull:#?}"
);
let pull_id = serde_json::to_string(&pull["id"]).expect("json");
// One entry per requested item, and the entry is the section itself.
live.send(&format!(r#"{{"jsonrpc":"2.0","id":{pull_id},"result":[{{"indent":4}}]}}"#));
live.send(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string("module pull_me;\nwire a;\nendmodule\n").expect("json")
));
live.send(&format(2));
let pulled = live.wait_for(|m| m["id"] == 2);
assert_eq!(
pulled["result"][0]["newText"],
serde_json::json!("module pull_me;\n wire a;\nendmodule\n"),
"the pulled indent beats the editor's tabSize=2: {pulled:#?}"
);
// An empty `didChangeConfiguration` is the modern "come and ask again",
// not a settings payload that clears everything.
live.send(r#"{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{"settings":null}}"#);
let again = live.wait_for(|m| m["method"] == "workspace/configuration");
let again_id = serde_json::to_string(&again["id"]).expect("json");
live.send(&format!(r#"{{"jsonrpc":"2.0","id":{again_id},"result":[{{"indent":8}}]}}"#));
live.send(&format(3));
let repulled = live.wait_for(|m| m["id"] == 3);
assert_eq!(
repulled["result"][0]["newText"],
serde_json::json!("module pull_me;\n wire a;\nendmodule\n"),
"{repulled:#?}"
);
// And a client with nothing to say answers `null`, which is the defaults.
live.send(
r#"{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{"settings":{}}}"#,
);
let empty = live.wait_for(|m| m["method"] == "workspace/configuration");
let empty_id = serde_json::to_string(&empty["id"]).expect("json");
live.send(&format!(r#"{{"jsonrpc":"2.0","id":{empty_id},"result":[null]}}"#));
live.send(&format(4));
let defaulted = live.wait_for(|m| m["id"] == 4);
assert_eq!(
defaulted["result"][0]["newText"],
serde_json::json!("module pull_me;\n wire a;\nendmodule\n"),
"the tab size is back in charge: {defaulted:#?}"
);
live.finish();
let _ = std::fs::remove_dir_all(&dir);
}
/// index-scope (2026-08-28): the *shipped* `scopeDepth`, over the real wire.
///
/// `performance.md` §4 measured the old default of 0 indexing exactly one file
/// when opening `hw/ip/aes/dv/tb/tb.sv` in opentitan — `dv/tb/` holds only
/// `tb.sv` — so definition, hover, references and `workspace/symbol` all
/// answered nothing until some later jump widened the scope. The default is 2
/// now, and this pins all three rungs of that decision on the same tree: what
/// the shipped depth reaches, that the climb clamps at the workspace root, and
/// that an explicit `0` is still exactly what it always was.
#[test]
fn the_shipped_scope_depth_reaches_the_block_a_file_belongs_to() {
let dir = temp_dir("scopedepthdefault");
let outside = temp_dir("scopedepthoutside");
let package = |path: PathBuf, name: &str| {
std::fs::create_dir_all(path.parent().expect("a parent")).expect("dirs");
std::fs::write(&path, format!("package {name};\n localparam WIDTH = 8;\nendpackage\n"))
.expect("write");
};
// The opentitan shape: a block with its RTL and its testbench two folders
// apart, a *second* block beside it, and a file at the workspace root.
package(dir.join("hw/ip/aes/rtl/aes.sv"), "aes_pkg");
package(dir.join("hw/ip/kmac/rtl/kmac.sv"), "kmac_pkg");
package(dir.join("root.sv"), "root_pkg");
package(outside.join("outside.sv"), "outside_pkg");
let tb = dir.join("hw/ip/aes/dv/tb/tb.sv");
let tb_text = "module tb;\n localparam W = aes_pkg::WIDTH;\nendmodule\n";
std::fs::create_dir_all(tb.parent().expect("a parent")).expect("dirs");
std::fs::write(&tb, tb_text).expect("write");
let root = format!("file://{}", dir.display());
let tb_uri = format!("file://{}", tb.display());
let query = |id: u32, name: &str| {
frame(&format!(
r#"{{"jsonrpc":"2.0","id":{id},"method":"workspace/symbol","params":{{"query":"{name}"}}}}"#
))
};
let depth = |n: u32| {
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{{"settings":{{"lucisv":{{"index":{{"scopeDepth":{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":"{tb_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string(tb_text).expect("json")
)),
// Nothing has been widened and no setting has been touched: this is
// what a user gets the moment they open a testbench.
query(2, "aes_pkg"),
query(3, "kmac_pkg"),
// The block, not the world — so the definition in the buffer resolves.
frame(&format!(
r#"{{"jsonrpc":"2.0","id":4,"method":"textDocument/definition","params":{{"textDocument":{{"uri":"{tb_uri}"}},"position":{{"line":1,"character":27}}}}}}"#
)),
// An explicit 0 is the old behaviour, unchanged: `dv/tb/` alone, which
// holds nothing but the open buffer.
depth(0),
query(5, "aes_pkg"),
// And the climb clamps at the workspace root however high it is asked
// to go — the root's own file is reached, and nothing outside it is.
depth(99),
query(6, "root_pkg"),
query(7, "outside_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, "two levels up from dv/tb is the aes block, rtl and all");
assert_eq!(hits(3), 0, "and stops there: the block beside it is not in scope");
assert_eq!(hits(4), 1, "so the testbench's reference into the RTL resolves at once");
assert_eq!(hits(5), 0, "an explicit 0 is the file's own folder, exactly as before");
assert_eq!(hits(6), 1, "a depth of 99 climbs to the workspace root");
assert_eq!(hits(7), 0, "and no further: nothing outside the root is indexed");
let _ = std::fs::remove_dir_all(&dir);
let _ = std::fs::remove_dir_all(&outside);
}
/// index-scope (2026-08-27): the default folder scope over the real wire.
///
/// What only an e2e test can settle: that the narrowing is what a *client*
/// sees, not just what `Workspace` computes — a definition into a sibling
/// folder answers nothing until a buffer in that folder widens the scope, and
/// a client that asked for `lucisv.index.scope: "workspace"` never sees the
/// narrow answer at all.
#[test]
fn the_folder_scope_widens_when_a_file_in_another_folder_is_opened() {
let dir = temp_dir("indexscope");
std::fs::create_dir_all(dir.join("rtl")).expect("rtl");
std::fs::create_dir_all(dir.join("include")).expect("include");
let top = dir.join("rtl/scope_top.sv");
let top_text = "module scope_top;\n localparam W = scope_defs::WIDTH;\nendmodule\n";
std::fs::write(&top, top_text).expect("write");
let defs = dir.join("include/scope_defs.sv");
let defs_text = "package scope_defs;\n localparam WIDTH = 8;\nendpackage\n";
std::fs::write(&defs, defs_text).expect("write");
let root = format!("file://{}", dir.display());
let top_uri = format!("file://{}", top.display());
let defs_uri = format!("file://{}", defs.display());
// The cursor on `WIDTH` in `scope_defs::WIDTH`.
let definition = |id: u32| {
format!(
r#"{{"jsonrpc":"2.0","id":{id},"method":"textDocument/definition","params":{{"textDocument":{{"uri":"{top_uri}"}},"position":{{"line":1,"character":33}}}}}}"#
)
};
let open = |uri: &str, text: &str| {
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 mut live = Live::start();
live.send(&format!(
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
));
let _ = live.wait_for(|m| m["id"] == 1);
live.send(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#);
// `scopeDepth: 0` — the narrowest rung, and the shipped default until
// 2026-08-28. Asked for out loud so this test stays about the *widen*;
// what the shipped depth covers is
// `the_shipped_scope_depth_reaches_the_block_a_file_belongs_to`.
live.send(
r#"{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{"settings":{"lucisv":{"index":{"scopeDepth":0}}}}}"#,
);
live.send(&open(&top_uri, top_text));
live.send(&definition(2));
let narrow = live.wait_for(|m| m["id"] == 2);
assert_eq!(
narrow["result"].as_array().map(Vec::len),
Some(0),
"the package is in a sibling folder, which depth 0 does not cover: {narrow:#?}"
);
// Opening the other file widens the scope and rebuilds — no save, no
// settings change, just the file the user opened.
live.send(&open(&defs_uri, defs_text));
live.send(&definition(3));
let widened = live.wait_for(|m| m["id"] == 3);
let targets = widened["result"].as_array().expect("a location list");
assert_eq!(targets.len(), 1, "{widened:#?}");
assert_eq!(targets[0]["uri"], defs_uri.as_str(), "{widened:#?}");
live.finish();
// And the migration setting: the same session, the same first question,
// answered straight away.
let mut wide = Live::start();
wide.send(&format!(
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
));
let _ = wide.wait_for(|m| m["id"] == 1);
wide.send(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#);
wide.send(WIDE_SCOPE);
wide.send(&open(&top_uri, top_text));
wide.send(&definition(2));
let immediate = wide.wait_for(|m| m["id"] == 2);
let targets = immediate["result"].as_array().expect("a location list");
assert_eq!(targets.len(), 1, "the whole workspace was indexed: {immediate:#?}");
assert_eq!(targets[0]["uri"], defs_uri.as_str(), "{immediate:#?}");
wide.finish();
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_save_of_one_file_updates_the_index_over_the_wire() {
// The incremental path against the real binary: a save rewrites one file,
// the answer that file supplies changes, and a second file nobody touched
// still answers exactly what it did before.
let dir = temp_dir("incremental");
std::fs::write(dir.join("sub.sv"), "module sub;\nendmodule\n").expect("write");
std::fs::write(dir.join("other.sv"), "module other;\nendmodule\n").expect("write");
let top = dir.join("top.sv");
let before = "module top;\n sub u1 ();\nendmodule\n";
std::fs::write(&top, before).expect("write");
let root = format!("file://{}", dir.display());
let uri = format!("file://{}", top.display());
// After the save `top.sv` instantiates `other` instead of `sub`. Both
// definition requests are asked twice, once each side of the save.
let after = "module top;\n other u1 ();\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(WIDE_SCOPE),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string(before).expect("json")
)),
// Where `sub` is instantiated, before: line 1, character 2.
frame(&format!(
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/definition","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":1,"character":3}}}}}}"#
)),
// And what the untouched second file's own declaration answers, out
// of the index rather than out of a buffer — the file has none.
frame(
r#"{"jsonrpc":"2.0","id":3,"method":"workspace/symbol","params":{"query":"sub"}}"#,
),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didSave","params":{{"textDocument":{{"uri":"{uri}"}},"text":{}}}}}"#,
serde_json::to_string(after).expect("json")
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":4,"method":"textDocument/definition","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":1,"character":3}}}}}}"#
)),
frame(
r#"{"jsonrpc":"2.0","id":5,"method":"workspace/symbol","params":{"query":"sub"}}"#,
),
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 answer = |id: i64| -> serde_json::Value {
messages
.iter()
.find(|m| m["id"] == id)
.unwrap_or_else(|| panic!("no answer to {id} in {messages:#?}"))["result"]
.clone()
};
// `textDocument/definition` answers a list of locations.
let target =
|id: i64| -> String { answer(id)[0]["uri"].as_str().unwrap_or_default().to_string() };
assert!(target(2).ends_with("sub.sv"), "premise: {:#?}", answer(2));
assert!(target(4).ends_with("other.sv"), "the save moved the answer to `other.sv`");
assert_eq!(answer(3), answer(5), "the file nobody touched answers exactly what it did");
assert!(
answer(3).as_array().is_some_and(|hits| hits.iter().any(|hit| hit["name"] == "sub")),
"premise: it answers at all — {:#?}",
answer(3)
);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_second_session_over_the_same_storage_path_indexes_from_the_cache() {
// The owner's case on the wire, with the real binary: one session indexes
// a workspace and writes what it learned into the folder the client named
// in `initializationOptions.storagePath`; a second session over the same
// folder gets the same index without parsing a file
// (docs/features/index-persistence/README.md).
let dir = temp_dir("persist");
let storage = temp_dir("persist_storage");
std::fs::write(dir.join("a.sv"), "module a;\nendmodule\n").expect("write");
std::fs::write(dir.join("b.sv"), "module b;\nendmodule\n").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}","initializationOptions":{{"storagePath":{}}},"capabilities":{{"window":{{"workDoneProgress":true}}}}}}}}"#,
serde_json::to_string(&storage.display().to_string()).expect("json")
)),
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
// The scope push is what makes the workspace really get walked;
// it also rescans, which is the scan these assertions are about.
frame(WIDE_SCOPE),
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
]
.concat()
};
/// Every `window/logMessage` line of a transcript.
fn log_lines(messages: &[serde_json::Value]) -> Vec<String> {
messages
.iter()
.filter(|m| m["method"] == "window/logMessage")
.filter_map(|m| m["params"]["message"].as_str().map(str::to_string))
.collect()
}
/// Every progress `end` message of a transcript.
fn ends(messages: &[serde_json::Value]) -> Vec<String> {
messages
.iter()
.filter(|m| m["params"]["value"]["kind"] == "end")
.filter_map(|m| m["params"]["value"]["message"].as_str().map(str::to_string))
.collect()
}
let cold = talk(&session());
assert_eq!(ends(&cold), ["0 files indexed", "2 files indexed"], "{cold:#?}");
let parsed: Vec<String> =
log_lines(&cold).into_iter().filter(|l| l.starts_with("indexing: ")).collect();
assert_eq!(parsed.len(), 2, "the first session parses both files: {parsed:?}");
assert!(
storage.join("index-cache").exists(),
"and writes what it found where the client said: {}",
storage.display()
);
let warm = talk(&session());
assert_eq!(
ends(&warm),
["0 files indexed", "2 files indexed, 2 from cache"],
"the second session's bar says where its files came from: {warm:#?}"
);
let lines = log_lines(&warm);
assert_eq!(
lines.iter().filter(|l| l.starts_with("cached: ")).count(),
2,
"and its log names them one by one: {lines:?}"
);
assert!(
!lines.iter().any(|l| l.starts_with("indexing: ")),
"with nothing parsed at all: {lines:?}"
);
// A file changed between sessions is the only thing the third one parses.
std::fs::write(dir.join("b.sv"), "module b_renamed;\nendmodule\n").expect("write");
let half = talk(&session());
let lines = log_lines(&half);
assert_eq!(lines.iter().filter(|l| l.starts_with("cached: ")).count(), 1, "{lines:?}");
assert_eq!(lines.iter().filter(|l| l.starts_with("indexing: ")).count(), 1, "{lines:?}");
assert_eq!(ends(&half), ["0 files indexed", "2 files indexed, 1 from cache"], "{half:#?}");
let _ = std::fs::remove_dir_all(&dir);
let _ = std::fs::remove_dir_all(&storage);
}
/// A 5 MB netlist — over the shipped `lucisv.largeFile.threshold` of 4 MiB,
/// so this needs no settings push to reach the fast path.
fn big_netlist() -> String {
let mut text = String::from("module netlist_top;\n wire needle;\n");
let mut n = 0u64;
while text.len() < 5 * 1024 * 1024 {
text.push_str(&format!(" inv_2 _{n}_ (.A(net{n}), .Y(needle));\n"));
n += 1;
}
text.push_str("endmodule\n");
text
}
#[test]
fn a_five_megabyte_buffer_opens_on_the_fast_path_over_the_wire() {
// The one thing the handler tests cannot show: that a buffer far too big
// to analyze goes through the real binary, over real framing, at the
// shipped default threshold — and that what comes back is colour for the
// window, an answer for the scans, an error for the format, and a decline
// for `semanticTokens/full`.
let dir = temp_dir("largefile");
let file = dir.join("netlist.v");
let text = big_netlist();
std::fs::write(&file, &text).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(&text).expect("json")
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/semanticTokens/range","params":{{"textDocument":{{"uri":"{uri}"}},"range":{{"start":{{"line":1,"character":0}},"end":{{"line":3,"character":0}}}}}}}}"#
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/semanticTokens/full","params":{{"textDocument":{{"uri":"{uri}"}}}}}}"#
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":4,"method":"textDocument/definition","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":1,"character":9}}}}}}"#
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":5,"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 clock = std::time::Instant::now();
let messages = talk(&session);
let elapsed = clock.elapsed();
// The window painted, in the file's own coordinates.
let ranged = messages.iter().find(|m| m["id"] == 2).expect("range response");
let window = token_numbers(&ranged["result"]["data"]);
assert!(!window.is_empty(), "the viewport was coloured: {ranged:#?}");
assert_eq!(window.len() % 5, 0, "five numbers per token");
assert_eq!(window[0], 1, "starting on the window's own first line");
// `full` is declined, not answered — see the feature README for why an
// empty answer would cost the file all of its colour.
let full = messages.iter().find(|m| m["id"] == 3).expect("full response");
assert!(full["result"].is_null(), "no result at all: {full:#?}");
assert_eq!(full["error"]["code"], -32801, "ContentModified for a client that said nothing");
assert!(
full["error"]["message"].as_str().unwrap_or("").contains("largeFile.threshold"),
"{full:#?}"
);
// The scan answered, in this file.
let definition = messages.iter().find(|m| m["id"] == 4).expect("definition response");
let locations = definition["result"].as_array().expect("an array");
assert_eq!(locations.len(), 1, "{definition:#?}");
assert_eq!(locations[0]["range"]["start"]["line"], 1);
// Formatting refuses, out loud, and edits nothing.
let formatting = messages.iter().find(|m| m["id"] == 5).expect("formatting response");
assert_eq!(formatting["result"], serde_json::json!([]), "{formatting:#?}");
let shown: Vec<String> = messages
.iter()
.filter(|m| m["method"] == "window/showMessage")
.filter_map(|m| m["params"]["message"].as_str().map(str::to_string))
.collect();
assert_eq!(shown.len(), 1, "{shown:?}");
assert!(shown[0].contains("cannot format"), "{shown:?}");
// And the fast path announced itself once.
let announced: Vec<String> = messages
.iter()
.filter(|m| m["method"] == "window/logMessage")
.filter_map(|m| m["params"]["message"].as_str().map(str::to_string))
.filter(|line| line.starts_with("lucisv: large-file fast path:"))
.collect();
assert_eq!(announced.len(), 1, "{announced:?}");
// The whole session — 5 MB across a pipe and back — in a debug build.
// 0.4 s on the machine this was written on, and the bound is twenty-five
// times that: the point is that nothing here parses five megabytes of
// Verilog, which in a debug build is minutes.
assert!(elapsed.as_secs() < 10, "the session took {elapsed:?}");
eprintln!("5 MB fast-path session: {elapsed:?}");
let _ = std::fs::remove_dir_all(&dir);
}
// ----------------------------------------------------------------------
// Interactive latency — a measurement, not an assertion
// ----------------------------------------------------------------------
//
// `docs/perf/README.md` records what one flush costs by calling the pieces
// directly. What it could not record from inside the crate is the number a
// user actually feels: the wall time from the `didChange` an editor sends on
// a keystroke to the `publishDiagnostics` that redraws the squiggles. That
// round trip crosses two pipes, a JSON encoder and decoder, the change
// debounce's quiet-period timer and a whole `Document::new`, and only a
// session against the real binary can time it.
//
// Like every measurement in `crates/lucisv_server/src/perf.rs` this asserts
// nothing about duration — a test that fails when the machine is busy is a
// test that gets deleted — and is `#[ignore]`d so an ordinary `cargo test`
// never pays for it.
/// A generated module of about `lines` lines, ending in a comment line for
/// keystrokes to land on.
///
/// A copy of `perf::generated_module`, because `lucisv_server` is a binary
/// crate and an integration test cannot reach into its modules. The two
/// differ in one line only — the trailing `// typing` comment this version
/// adds for a keystroke to land on, which is trivia and not a token — and
/// they must stay that close, or the two tables in `docs/perf/README.md`
/// stop being readable against one another.
fn generated_module(name: &str, lines: usize) -> String {
let mut src = format!(
"module {name} (\n input logic clk,\n input logic rst_n,\n \
input logic [31:0] data_in,\n output logic [31:0] data_out\n);\n"
);
for n in 0..lines.saturating_sub(8) / 4 {
src.push_str(&format!(
" wire [31:0] w_{n};\n \
assign w_{n} = data_in ^ {{32{{rst_n}}}};\n \
reg [31:0] r_{n};\n \
always @(posedge clk) r_{n} <= w_{n};\n"
));
}
src.push_str(" assign data_out = data_in;\n // typing\nendmodule\n");
src
}
/// One keystroke: an `x` typed at `character` on `line`, as an editor with
/// incremental sync sends it.
fn keystroke(uri: &str, version: u32, line: u32, character: u32) -> String {
format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didChange","params":{{"textDocument":{{"uri":"{uri}","version":{version}}},"contentChanges":[{{"range":{{"start":{{"line":{line},"character":{character}}},"end":{{"line":{line},"character":{character}}}}},"text":"x"}}]}}}}"#
)
}
/// `cargo test --release -p lucisv_server --test e2e a_keystroke -- --ignored --nocapture --test-threads=1`
#[test]
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
fn a_keystroke_round_trip_over_the_wire() {
for lines in [1_000usize, 10_000] {
let dir = temp_dir(&format!("latency{lines}"));
let file = dir.join("gen.sv");
let source = generated_module("gen", lines);
std::fs::write(&file, &source).expect("write");
let root = format!("file://{}", dir.display());
let uri = format!("file://{}", file.display());
// The `// typing` line, 0-based, and the column just past its text.
let comment = source.find(" // typing").expect("the typing line");
let line = source[..comment].matches('\n').count() as u32;
let column = " // typing".len() as u32;
let mut live = Live::start();
live.send(&format!(
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
));
live.wait_for(|m| m["id"] == 1);
live.send(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#);
live.send(WIDE_SCOPE);
live.send(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string(&source).expect("json")
));
live.wait_for(|m| m["method"] == "textDocument/publishDiagnostics");
// One keystroke, alone. Nothing else is coming, so what ends the wait
// is the debounce's quiet-period timer: this is that timer, plus one
// flush, plus the wire.
let started = std::time::Instant::now();
live.send(&keystroke(&uri, 2, line, column));
live.wait_for(|m| m["method"] == "textDocument/publishDiagnostics");
let single = started.elapsed();
// The same keystroke, followed straight away by a request — which is
// what a real editor does: VS Code asks for semantic tokens, inlay
// hints and highlights the moment the buffer changes. A request
// flushes the dirty buffer before it is answered, so the quiet-period
// timer never runs and this is the flush and the wire alone.
// Ten of them, and the mean: no timer is involved, so these are short
// enough that a single one would be mostly scheduling noise.
let runs = 10u32;
let started = std::time::Instant::now();
for k in 0..runs {
live.send(&keystroke(&uri, 3 + k, line, column));
live.send(&format!(
r#"{{"jsonrpc":"2.0","id":{},"method":"textDocument/documentHighlight","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":{line},"character":4}}}}}}"#,
50 + k
));
live.wait_for(|m| m["method"] == "textDocument/publishDiagnostics");
live.wait_for(|m| m["id"] == 50 + k);
}
let requested = started.elapsed() / runs;
// Ten keystrokes with no pause between them — a burst of typing. The
// debounce's whole claim is that this costs one flush and not ten,
// and the count below is that claim measured rather than reasoned
// about: the wait consumes one publish and `finish` counts every
// other one still queued when the shutdown reply comes back.
//
// This is deliberately the *last* thing measured. Every `wait_for`
// above accepts any publish, so a second one the burst had produced
// would be absorbed by whichever wait ran next and never counted —
// with nothing between the burst and `finish`, there is no such wait.
let started = std::time::Instant::now();
for k in 0..10u32 {
live.send(&keystroke(&uri, 13 + k, line, column + 1 + k));
}
live.wait_for(|m| m["method"] == "textDocument/publishDiagnostics");
let burst = started.elapsed();
let published = 1 + live.finish();
eprintln!(
"keystroke round trip, {lines} lines: one change alone {single:?}, \
a burst of ten {burst:?} for {published} publish(es), \
one change a request follows {requested:?}"
);
let _ = std::fs::remove_dir_all(&dir);
}
}
/// `cargo test --release -p lucisv_server --test e2e a_hover_issued -- --ignored --nocapture --test-threads=1`
#[test]
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
fn a_hover_issued_during_the_initial_scan_is_answered_during_it() {
// The probe the hover-latency round left behind, now measuring the other
// side of the change it filed for. It used to read
// `..._waits_for_it`, because `Server::new` ran the whole startup scan
// *before* `run()`'s message loop took its first message and anything a
// client sent the moment it had sent `initialized` sat in the OS pipe
// until that scan was done: 780 ms cold / 287 ms warm over these 200
// files. The scan now answers messages between its files
// (`docs/features/scan-interleave/README.md`), so what this prints is
// one file's step and not a whole scan.
//
// A `lucisv.toml` naming a filelist is what makes the startup scan index
// the whole tree: it is the top rung of the scope ladder and the only one
// that answers before any buffer has been opened.
let dir = temp_dir("firsthover");
let files = 200usize;
let mut list = String::new();
for n in 0..files {
let name = format!("m{n}.sv");
std::fs::write(dir.join(&name), generated_module(&format!("m{n}"), 1_000)).expect("write");
list.push_str(&format!("{name}\n"));
}
std::fs::write(dir.join("files.f"), &list).expect("write");
let top = "module top;\n m7 u (.data_in(32'h0));\nendmodule\n";
let top_path = dir.join("top.sv");
std::fs::write(&top_path, top).expect("write");
std::fs::write(dir.join("lucisv.toml"), "filelist = \"files.f\"\n").expect("write");
// `top.sv` is not in the filelist, so it is not indexed — but it is what
// the hover is *issued from*, and a buffer is indexed by being opened.
std::fs::write(dir.join("files.f"), format!("{list}top.sv\n")).expect("write");
let root = format!("file://{}", dir.display());
let uri = format!("file://{}", top_path.display());
let hover = |id: u32| {
format!(
r#"{{"jsonrpc":"2.0","id":{id},"method":"textDocument/hover","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":1,"character":3}}}}}}"#
)
};
// Two whole sessions over the same storage folder: the first fills the
// persistent index cache, the second reads it. Both are measured, because
// "does the cache fix this?" is the second half of the question — it makes
// the scan cheaper, and the first hover still waits out whatever is left.
let mut took = Vec::new();
for session in 0..2 {
let mut live = Live::start();
// The progress capability is what makes "the scan is over" observable
// to the client, and therefore to the second measurement below.
live.send(&format!(
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{"window":{{"workDoneProgress":true}}}},"initializationOptions":{{"storagePath":"{}"}}}}}}"#,
dir.join("storage").display()
));
live.wait_for(|m| m["id"] == 1);
// Everything a client sends the instant the handshake is done, in one
// go — which is exactly what VS Code does with the editor already open.
let started = std::time::Instant::now();
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(top).expect("json")
));
live.send(&hover(2));
live.wait_for(|m| m["id"] == 2);
let queued_behind_the_scan = started.elapsed();
// The same hover, with the scan long finished — which is where the
// cross-file answer is required, because *that* one reads a finished
// index. The mid-scan one above reads the index as of the moment it
// was asked, and `m7.sv` sorts a long way down 200 paths.
live.wait_for(|m| m["params"]["value"]["kind"] == "end");
let started = std::time::Instant::now();
live.send(&hover(3));
let done = live.wait_for(|m| m["id"] == 3);
let after_the_scan = started.elapsed();
assert!(
format!("{done:#?}").contains("m7.sv"),
"the hover must really answer across files once the scan is done: {done:#?}"
);
live.finish();
took.push((session, queued_behind_the_scan, after_the_scan));
}
for (session, behind, after) in took {
let store = if session == 0 { "cold store" } else { "warm store" };
eprintln!(
"hover issued the moment `initialized` was sent, over {files} files of 1k lines \
({store}): {behind:?}; the same hover once the scan is done: {after:?}"
);
}
let _ = std::fs::remove_dir_all(&dir);
}
/// A generated many-folder workspace: `folders` directories of `each` files,
/// every one declaring a package named after where it lives.
///
/// The shape the owner's report is about — a project too big to walk, browsed
/// one folder at a time — without depending on any checkout being present.
fn many_folders(name: &str, folders: usize, each: usize) -> PathBuf {
let dir = temp_dir(name);
for folder in 0..folders {
let path = dir.join(format!("blk{folder:02}/rtl"));
std::fs::create_dir_all(&path).expect("folder");
for file in 0..each {
std::fs::write(
path.join(format!("f{file:02}.sv")),
format!(
"package b{folder:02}_f{file:02};\n localparam WIDTH = {file};\nendpackage\n"
),
)
.expect("write");
}
}
dir
}
/// What each indexing bar read, split by where it came from: the files it read
/// off **disk** (`indexing:`), and the open buffers it took from the analysis
/// they already held (`analyzed:`). Paths are shortened to their last three
/// components, which is `<folder>/rtl/<file>` in this fixture.
///
/// The honest wire-level answer to "what did that scan actually do?": the
/// per-file log is `lucisv.index.logFiles`, on by default, and it names one
/// line per file the scan took.
fn work_per_bar(messages: &[serde_json::Value]) -> Vec<(Vec<String>, Vec<String>)> {
let mut bars: Vec<(Vec<String>, Vec<String>)> = Vec::new();
let tail = |path: &str| {
let mut parts: Vec<&str> = path.rsplit('/').take(3).collect();
parts.reverse();
parts.join("/")
};
for message in messages {
let kind = message["params"]["value"]["kind"].as_str();
if message["method"] == "$/progress" && kind == Some("begin") {
bars.push((Vec::new(), Vec::new()));
}
if message["method"] == "window/logMessage" {
let Some(line) = message["params"]["message"].as_str() else { continue };
let Some(bar) = bars.last_mut() else { continue };
if let Some(path) = line.strip_prefix("indexing: ") {
bar.0.push(tail(path));
} else if let Some(path) = line.strip_prefix("analyzed: ") {
bar.1.push(tail(path));
}
}
}
bars
}
#[test]
fn a_jump_into_a_new_folder_indexes_that_folder_and_not_the_ones_before_it() {
// The owner's opentitan report, in miniature and with no opentitan: 24
// folders of 20 files, browsed one jump at a time. Every widening
// `didOpen` must read the folder it opened and **nothing else** — the log
// is what says so, file by file — while the answers stay exactly what the
// whole-rescan widen gave.
let dir = many_folders("widenfolders", 24, 20);
let root = format!("file://{}", dir.display());
let file = |folder: usize, n: usize| dir.join(format!("blk{folder:02}/rtl/f{n:02}.sv"));
let uri = |folder: usize, n: usize| format!("file://{}", file(folder, n).display());
let text = |folder: usize, n: usize| std::fs::read_to_string(file(folder, n)).expect("read");
let open = |folder: usize, n: usize| {
format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
uri(folder, n),
serde_json::to_string(&text(folder, n)).expect("json")
)
};
// The cursor on `WIDTH` of the reference this file makes into another
// folder's package.
let jump = |id: u32, folder: usize, n: usize| {
format!(
r#"{{"jsonrpc":"2.0","id":{id},"method":"workspace/symbol","params":{{"query":"b{folder:02}_f{n:02}"}}}}"#
)
};
let session = [
frame(&format!(
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{"window":{{"workDoneProgress":true}}}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
// `scopeDepth: 0`, asked for out loud: at the shipped depth of 2 the
// first `didOpen` in `blk00/rtl/` would raise to the workspace root
// and index all 24 folders at once, which is a test of the clamp
// rather than of the widen this one is about.
frame(
r#"{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{"settings":{"lucisv":{"index":{"scopeDepth":0}}}}}"#,
),
frame(&open(0, 0)),
frame(&open(1, 0)),
frame(&open(2, 0)),
// A second file in a folder already reached: no bar at all.
frame(&open(2, 5)),
frame(&jump(2, 1, 7)),
frame(&jump(3, 23, 7)),
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 bars = work_per_bar(&messages);
// Five bars: the empty startup scan, the equally empty rescan the
// `scopeDepth` push asks for, then one per widening `didOpen`. The fourth
// `didOpen` is in a folder already covered and asks for none.
assert_eq!(bars.len(), 5, "one bar per widen and no more: {bars:#?}");
assert_eq!(
bars[..2],
[(vec![], vec![]), (vec![], vec![])],
"neither the startup scan nor the settings rescan indexes anything: nothing is open"
);
for (folder, (read, reused)) in bars[2..].iter().enumerate() {
// **The round, on the wire.** Each jump reads the 19 disk files of the
// folder it opened — `f00.sv` there is the buffer, so it is reused
// rather than read — and never the 19, 38 or 57 of the folders reached
// before it, which is what every one of these bars re-read until now.
let mine: Vec<String> = (1..20).map(|n| format!("blk{folder:02}/rtl/f{n:02}.sv")).collect();
assert_eq!(read, &mine, "bar {} read the wrong files", folder + 1);
// And every open buffer is refreshed from the analysis it holds, which
// is what carries an unsaved edit across a widen.
let buffers: Vec<String> = (0..=folder).map(|b| format!("blk{b:02}/rtl/f00.sv")).collect();
assert_eq!(reused, &buffers, "bar {} reused the wrong buffers", folder + 1);
}
// And the answers are the whole-rescan ones: a package in a folder that
// has been jumped into resolves, one in a folder that has not does not.
let reached = messages.iter().find(|m| m["id"] == 2).expect("a symbol response");
assert_eq!(
reached["result"].as_array().map(Vec::len),
Some(1),
"a package in a folder the scope has reached: {reached:#?}"
);
let unreached = messages.iter().find(|m| m["id"] == 3).expect("a symbol response");
assert_eq!(
unreached["result"].as_array().map(Vec::len),
Some(0),
"and scope semantics are unchanged: an unopened folder is still invisible: {unreached:#?}"
);
let _ = std::fs::remove_dir_all(&dir);
}
// ----------------------------------------------------------------------
// `--verbose` — per-operation timing, over the wire
// ----------------------------------------------------------------------
/// Every `timing:` line the server said, in the order it said them.
///
/// They arrive as `window/logMessage` at `MessageType::LOG` (5), which is the
/// channel the per-file index log already uses — a client that shows one shows
/// both. The prefix is the whole of what tells them apart.
fn timing_lines(messages: &[serde_json::Value]) -> Vec<String> {
messages
.iter()
.filter(|m| m["method"] == "window/logMessage")
.filter_map(|m| m["params"]["message"].as_str())
.filter(|line| line.starts_with("timing: "))
.map(str::to_string)
.collect()
}
/// A whole session over one small buffer: open it, type in it, ask two
/// questions about it, save it, shut down. Every kind of timing line but the
/// held one comes out of this, and nothing in it takes long enough to make an
/// assertion timing-dependent.
fn timed_session(dir: &Path) -> String {
let file = dir.join("top.sv");
let source = "module top;\n wire a;\n initial a = 1;\nendmodule\n// c\n";
std::fs::write(&file, source).expect("write");
let root = format!("file://{}", dir.display());
let uri = format!("file://{}", file.display());
[
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")
)),
// One keystroke inside the trailing comment: the buffer goes dirty,
// and the request behind it is what flushes it.
frame(&keystroke(&uri, 2, 4, 4)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/documentSymbol","params":{{"textDocument":{{"uri":"{uri}"}}}}}}"#
)),
// A save of a file the index already holds: the incremental path, not
// a whole rebuild.
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didSave","params":{{"textDocument":{{"uri":"{uri}"}}}}}}"#
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/hover","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":2,"character":10}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
]
.concat()
}
#[test]
fn the_flag_times_every_request_and_notification_and_says_so_in_the_log_channel() {
let dir = temp_dir("verbose_on");
let messages = talk_with(&["--verbose"], &timed_session(&dir));
let lines = timing_lines(&messages);
assert!(!lines.is_empty(), "`--verbose` must say something: {messages:#?}");
// A line per request, and the wording is the contract: the owner has read
// these for two diagnostic builds, and a `grep timing:` over an output
// channel is how this feature is used.
let answered = |method: &str| {
lines.iter().any(|line| {
line.starts_with(&format!("timing: {method} answered in ")) && line.ends_with(" ms")
})
};
assert!(answered("textDocument/documentSymbol"), "{lines:#?}");
assert!(answered("textDocument/hover"), "{lines:#?}");
// `shutdown` is deliberately absent: `handle_shutdown` answers it in the
// loop, ahead of the dispatch, so it never reaches the timed wrapper.
// Nothing measurable happens there, and a line for it would mean moving
// the handshake through code that has no business timing it.
assert!(!answered("shutdown"), "{lines:#?}");
// A line per notification, in the same shape with the other verb.
assert!(
lines.iter().any(|line| {
line.starts_with("timing: textDocument/didOpen handled in ") && line.ends_with(" ms")
}),
"{lines:#?}"
);
// And the scan lifecycle, both ends of it. This session's workspace is one
// file, so the counts are the small ones — what is pinned is the wording
// and that both ends arrive.
assert!(lines.iter().any(|line| line.starts_with("timing: scan started: ")), "{lines:#?}");
assert!(
lines.iter().any(|line| {
line.starts_with("timing: scan finished: ")
&& line.contains(" skipped, ")
&& line.contains(" from cache) in ")
&& line.ends_with(" ms")
}),
"{lines:#?}"
);
// And the widen lifecycle, which this session reaches by opening a file:
// the folder it added is named, because "which folder did that jump cost
// me?" is the question the line exists to answer
// (`docs/features/index-scope/README.md`).
assert!(
lines.iter().any(|line| {
line.starts_with("timing: widen started: 1 folder added: ")
&& line.ends_with(&dir.display().to_string())
}),
"{lines:#?}"
);
assert!(
lines.iter().any(|line| {
line.starts_with("timing: widen finished: ")
&& line.contains(" from cache) in ")
&& line.ends_with(" ms")
}),
"{lines:#?}"
);
// The two lines that name work nobody asked for by message: the flush of
// what was typed, and the one-file reindex a save costs.
assert!(
lines.iter().any(|line| {
line.starts_with("timing: flush of 1 dirty buffer took ") && line.ends_with(" ms")
}),
"{lines:#?}"
);
assert!(
lines.iter().any(|line| {
line.starts_with(&format!("timing: reindex_one({}", dir.join("top.sv").display()))
&& line.contains(") took ")
&& line.ends_with(" ms")
}),
"{lines:#?}"
);
// The stated ordering: a request's timing line goes out **before** the
// response it describes. Nothing keys off that — a `window/logMessage`
// carries no id — but it is the contract this round wrote down, and the
// only way to notice it change is to pin it.
let line_at = messages
.iter()
.position(|m| {
m["params"]["message"]
.as_str()
.is_some_and(|line| line.starts_with("timing: textDocument/hover answered in "))
})
.expect("the hover's timing line");
let response_at = messages.iter().position(|m| m["id"] == 3).expect("the hover's response");
assert!(
line_at < response_at,
"the line describes the response that follows it: {messages:#?}"
);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn without_the_flag_not_one_timing_line_is_ever_sent() {
// The other half, and the one that matters: the shipped spawn — no
// arguments, which is what `smoke.js` and every editor use — must be
// byte-for-byte as quiet as it was before this feature existed.
let dir = temp_dir("verbose_off");
let messages = talk(&timed_session(&dir));
assert_eq!(timing_lines(&messages), Vec::<String>::new(), "{messages:#?}");
// And it is the same session, really answered: a server that failed to
// start would also say nothing.
assert!(messages.iter().any(|m| m["id"] == 2), "the symbols were answered: {messages:#?}");
assert!(messages.iter().any(|m| m["id"] == 9), "and the shutdown: {messages:#?}");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_request_queued_behind_a_rescan_says_it_was_held() {
// The line the owner asked for by name, and the one a "why is my editor
// slow?" session is about: the request was not slow, it had not started.
//
// Driven through the real mid-scan machinery: a filelist of 100 files is
// the startup scan's work list — over `INTERLEAVE_ABOVE`, so the scan
// answers messages between its files — and the whole session is already on
// the wire when it begins. The settings push it drains asks for a rescan,
// which mid-scan is the `rescan_wanted` flag; every request behind it is
// owed that rescan's effect, so it waits. See
// `docs/features/scan-interleave/README.md`.
let dir = temp_dir("verbose_held");
let files = 100usize;
let mut list = String::new();
for n in 0..files {
let name = format!("m{n}.sv");
std::fs::write(dir.join(&name), generated_module(&format!("m{n}"), 200)).expect("write");
list.push_str(&format!("{name}\n"));
}
std::fs::write(dir.join("files.f"), &list).expect("write");
std::fs::write(dir.join("lucisv.toml"), "filelist = \"files.f\"\n").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":{}}"#),
// Changes which files exist, so it asks for a rebuild — the one thing
// a request behind it must not be answered ahead of.
frame(
r#"{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{"settings":{"lucisv":{"exclude":["no-such-directory"]}}}}"#,
),
frame(r#"{"jsonrpc":"2.0","id":2,"method":"workspace/symbol","params":{"query":"m7"}}"#),
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
]
.concat();
let messages = talk_with(&["--verbose"], &session);
let lines = timing_lines(&messages);
let held: Vec<&String> = lines.iter().filter(|line| line.contains(" HELD ")).collect();
assert!(
held.iter().any(|line| {
line.starts_with("timing: workspace/symbol HELD behind a rescan (answering=")
&& line.contains(", wanted=")
&& line.contains(", already held=")
}),
"the symbol request must say it waited: {lines:#?}"
);
// Held is not dropped: the order contract answers it once the rescan it
// was queued behind has run.
let answered = messages.iter().find(|m| m["id"] == 2).expect("the symbol response");
assert!(answered["error"].is_null(), "{answered:#?}");
assert!(
lines.iter().any(|line| line.starts_with("timing: workspace/symbol answered in ")),
"and it is timed like any other request: {lines:#?}"
);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn an_argument_the_server_does_not_take_is_refused_rather_than_ignored() {
// The spawn contract's new edge: no arguments and `--verbose` start a
// server, anything else exits 2 with one line on stderr. A client that
// misspelled the flag learns it here rather than wondering for a whole
// session why nothing is logged.
let refused = server_command()
.args(["--verbos"])
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.output()
.expect("the server binary starts");
assert_eq!(refused.status.code(), Some(2), "{refused:?}");
let said = String::from_utf8_lossy(&refused.stderr);
assert!(said.contains("unknown option: --verbos"), "{said}");
assert!(said.contains("usage: lucisv-server [--verbose]"), "{said}");
assert!(refused.stdout.is_empty(), "nothing LSP-shaped on stdout: {refused:?}");
}
// ----------------------------------------------------------------------
// class-member-access (TODO.md §15)
// ----------------------------------------------------------------------
/// The owner's DV shape in one file: `in_item.user_id` where `in_item` is a
/// `c1` handle. Hover, definition, references and rename all read the same two
/// resolution layers, so one session pins all four on the tail — the token
/// that answered nothing at all before 2026-09-01.
#[test]
fn a_class_handles_member_is_hovered_navigated_and_renamed() {
let dir = temp_dir("membersamefile");
let file = dir.join("dv.sv");
let text = "\
class u1;
rand bit [7:0] base_field;
endclass
class c1 extends u1;
rand bit user_id;
endclass
class class2;
bit address;
extern task update(c1 in_item);
endclass
task class2::update(c1 in_item);
address = in_item.user_id;
endtask
";
std::fs::write(&file, text).expect("write");
let root = format!("file://{}", dir.display());
let uri = format!("file://{}", file.display());
// Line 14 is ` address = in_item.user_id;`; column 22 sits inside the
// tail. Line 5 column 13 is the property's own declaration.
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(text).expect("json")
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/hover","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":14,"character":22}}}}}}"#
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/definition","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":14,"character":22}}}}}}"#
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":4,"method":"textDocument/references","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":5,"character":13}},"context":{{"includeDeclaration":false}}}}}}"#
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":5,"method":"textDocument/rename","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":5,"character":13}},"newName":"uid"}}}}"#
)),
// And the left-hand side, which is the out-of-class body seeing its
// own class's property.
frame(&format!(
r#"{{"jsonrpc":"2.0","id":6,"method":"textDocument/hover","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":14,"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 response {id} in {messages:#?}"))
};
let hover = response(2)["result"]["contents"]["value"].as_str().expect("hover markdown");
assert!(hover.contains("rand bit user_id"), "the declaration's own line: got {hover}");
assert!(hover.contains("**variable**"), "labelled as what it is: got {hover}");
let definition = &response(3)["result"];
let range = definition.get("range").unwrap_or(&definition[0]["range"]);
assert_eq!(range["start"]["line"], 5, "the property's declaration: {definition:#?}");
assert_eq!(range["start"]["character"], 11);
let references = response(4)["result"].as_array().expect("a list");
assert_eq!(references.len(), 1, "the tail use, and only it: {references:#?}");
assert_eq!(references[0]["range"]["start"]["line"], 14);
assert_eq!(references[0]["range"]["start"]["character"], 20);
let edits = &response(5)["result"]["changes"][&uri];
let edits = edits.as_array().expect("edits for the open file");
let lines: Vec<i64> =
edits.iter().filter_map(|e| e["range"]["start"]["line"].as_i64()).collect();
assert!(edits.iter().all(|e| e["newText"] == "uid"), "{edits:#?}");
assert!(lines.contains(&5) && lines.contains(&14), "declaration and tail: {edits:#?}");
let owned = response(6)["result"]["contents"]["value"].as_str().expect("hover markdown");
assert!(owned.contains("bit address"), "the method's own class's property: got {owned}");
let _ = std::fs::remove_dir_all(&dir);
}
/// The same three classes in three files. The tail now needs the workspace
/// index — for `user_id` one member-table lookup, for `base_field` a hop up
/// the `extends` chase — and a member of a class whose base is not in the
/// workspace at all answers nothing, quietly.
#[test]
fn a_class_handles_member_is_hovered_across_files() {
let dir = temp_dir("membercrossfile");
std::fs::write(dir.join("base.sv"), "class u1;\n rand bit [7:0] base_field;\nendclass\n")
.expect("write");
std::fs::write(
dir.join("c1.sv"),
"class c1 extends u1;\n rand bit user_id;\n rand bit feature1;\nendclass\n",
)
.expect("write");
let class2 = dir.join("class2.sv");
let text = "\
class class2;
bit address;
bit address2;
bit [7:0] address3;
extern task update(c1 in_item);
endclass
task class2::update(c1 in_item);
address = in_item.user_id;
address2 = in_item.feature1;
address3 = in_item.base_field;
endtask
";
std::fs::write(&class2, text).expect("write");
// A class whose base is vendored somewhere outside the workspace — the
// UVM shape. Nothing can answer `h.get_name`, and nothing may break.
let orphan = dir.join("orphan.sv");
let orphan_text = "\
class my_item extends uvm_sequence_item;
bit own;
endclass
module m;
my_item h;
initial y = h.get_name;
endmodule
";
std::fs::write(&orphan, orphan_text).expect("write");
let root = format!("file://{}", dir.display());
let uri = format!("file://{}", class2.display());
let orphan_uri = format!("file://{}", orphan.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(WIDE_SCOPE),
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")
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{orphan_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string(orphan_text).expect("json")
)),
// `in_item.user_id` — the member of the handle's own class.
frame(&format!(
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/hover","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":8,"character":22}}}}}}"#
)),
// `in_item.base_field` — one hop up the chase, in a third file.
frame(&format!(
r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/hover","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":10,"character":24}}}}}}"#
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":4,"method":"textDocument/definition","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":10,"character":24}}}}}}"#
)),
// A base nothing in the workspace declares.
frame(&format!(
r#"{{"jsonrpc":"2.0","id":5,"method":"textDocument/hover","params":{{"textDocument":{{"uri":"{orphan_uri}"}},"position":{{"line":6,"character":18}}}}}}"#
)),
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 response {id} in {messages:#?}"))
};
let own = response(2)["result"]["contents"]["value"].as_str().expect("hover markdown");
assert!(own.contains("c1.sv:2"), "named with its file and line: got {own}");
assert!(own.contains("rand bit user_id"), "the declaration's own line: got {own}");
let inherited = response(3)["result"]["contents"]["value"].as_str().expect("hover markdown");
assert!(inherited.contains("base.sv:2"), "one hop up the chase: got {inherited}");
assert!(inherited.contains("rand bit [7:0] base_field"), "got {inherited}");
let definition = &response(4)["result"];
let target = definition.get("uri").map_or(&definition[0], |_| definition);
assert!(
target["uri"].as_str().expect("a uri").ends_with("base.sv"),
"the jump follows the hover: {definition:#?}"
);
assert_eq!(target["range"]["start"]["line"], 1);
assert!(
response(5)["result"].is_null(),
"a base outside the workspace answers nothing: {:#?}",
response(5)
);
let _ = std::fs::remove_dir_all(&dir);
}
/// A member **chain** across three files: `item.hdr.addr`, where `item` is an
/// `item_t` in one file whose `hdr` is a `hdr_t` in another. The last link is
/// the one that needs `Def::type_name` in the index — the hop from the middle
/// link's declaration to its declared type — so hover, definition and a rename
/// fanning out from the property's own declaration all pin it (round 2 of
/// `docs/features/class-member-access/README.md`).
#[test]
fn a_member_chains_last_link_is_hovered_navigated_and_renamed() {
let dir = temp_dir("memberchain");
let hdr = dir.join("hdr.sv");
let hdr_text = "class hdr_t;\n rand bit [7:0] addr;\nendclass\n";
std::fs::write(&hdr, hdr_text).expect("write");
std::fs::write(dir.join("item.sv"), "class item_t;\n hdr_t hdr;\nendclass\n").expect("write");
let driver = dir.join("driver.sv");
let driver_text = "\
class driver;
item_t item;
task go();
x = item.hdr.addr;
endtask
endclass
";
std::fs::write(&driver, driver_text).expect("write");
let root = format!("file://{}", dir.display());
let hdr_uri = format!("file://{}", hdr.display());
let driver_uri = format!("file://{}", driver.display());
// driver.sv line 3 is ` x = item.hdr.addr;`; character 18 sits inside
// the third link. hdr.sv line 1 character 17 is the property itself.
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(WIDE_SCOPE),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{driver_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string(driver_text).expect("json")
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{hdr_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string(hdr_text).expect("json")
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/hover","params":{{"textDocument":{{"uri":"{driver_uri}"}},"position":{{"line":3,"character":18}}}}}}"#
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/definition","params":{{"textDocument":{{"uri":"{driver_uri}"}},"position":{{"line":3,"character":18}}}}}}"#
)),
// The middle link, which is answered in the second file.
frame(&format!(
r#"{{"jsonrpc":"2.0","id":4,"method":"textDocument/hover","params":{{"textDocument":{{"uri":"{driver_uri}"}},"position":{{"line":3,"character":14}}}}}}"#
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":5,"method":"textDocument/references","params":{{"textDocument":{{"uri":"{hdr_uri}"}},"position":{{"line":1,"character":17}},"context":{{"includeDeclaration":false}}}}}}"#
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":6,"method":"textDocument/rename","params":{{"textDocument":{{"uri":"{hdr_uri}"}},"position":{{"line":1,"character":17}},"newName":"address"}}}}"#
)),
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 response {id} in {messages:#?}"))
};
let hover = response(2)["result"]["contents"]["value"].as_str().expect("hover markdown");
assert!(hover.contains("hdr.sv:2"), "the third link's own file and line: got {hover}");
assert!(hover.contains("rand bit [7:0] addr"), "got {hover}");
let definition = &response(3)["result"];
let target = definition.get("uri").map_or(&definition[0], |_| definition);
assert!(
target["uri"].as_str().expect("a uri").ends_with("hdr.sv"),
"the jump follows the hover: {definition:#?}"
);
assert_eq!(target["range"]["start"]["line"], 1);
let middle = response(4)["result"]["contents"]["value"].as_str().expect("hover markdown");
assert!(middle.contains("item.sv:2"), "the middle link is its own answer: got {middle}");
let references = response(5)["result"].as_array().expect("a list");
assert_eq!(references.len(), 1, "the chain tail is posted: {references:#?}");
assert!(references[0]["uri"].as_str().expect("a uri").ends_with("driver.sv"));
assert_eq!(references[0]["range"]["start"]["line"], 3);
assert_eq!(references[0]["range"]["start"]["character"], 17);
let changes = &response(6)["result"]["changes"];
let driver_edits = changes[&driver_uri].as_array().expect("the chain tail is rewritten");
assert_eq!(driver_edits.len(), 1, "{changes:#?}");
assert_eq!(driver_edits[0]["newText"], "address");
assert_eq!(changes[&hdr_uri].as_array().expect("the declaration too").len(), 1);
let _ = std::fs::remove_dir_all(&dir);
}
/// An instance head: `u.clk_i` where `u` instantiates a module declared in
/// another file. The instance's declared type is the module, so the port is
/// hovered exactly as a class property is.
#[test]
fn an_instance_heads_port_is_hovered_across_files() {
let dir = temp_dir("instancehead");
std::fs::write(
dir.join("sub.sv"),
"module sub (input wire clk_i);\n wire internal;\nendmodule\n",
)
.expect("write");
let top = dir.join("top.sv");
let text =
"module m;\n sub u ();\n initial y = u.clk_i;\n initial z = u.internal;\nendmodule\n";
std::fs::write(&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(WIDE_SCOPE),
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")
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/hover","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":2,"character":17}}}}}}"#
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/hover","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":3,"character":18}}}}}}"#
)),
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 response {id} in {messages:#?}"))
};
let port = response(2)["result"]["contents"]["value"].as_str().expect("hover markdown");
assert!(port.contains("sub.sv:1"), "the port's own file and line: got {port}");
assert!(port.contains("clk_i"), "got {port}");
// A module exports its ports and parameters and nothing else, so an
// internal net of another file answers nothing rather than something —
// the round-2 ruling in the feature README.
assert!(
response(3)["result"].is_null(),
"an internal signal is not exported across files: {:#?}",
response(3)
);
let _ = std::fs::remove_dir_all(&dir);
}
// ----------------------------------------------------------------------
// interface-semantics (TODO.md §16)
// ----------------------------------------------------------------------
/// The two labels coverage_gaps C2 called wrong answers: an interface that
/// hovered as a "module", and a `b_if.mp` whose modport half hovered as
/// nothing at all. Three files, so both go through the workspace layer.
#[test]
fn an_interface_and_its_modport_hover_as_what_they_are() {
let dir = temp_dir("ifacehover");
std::fs::write(
dir.join("bus_if.sv"),
"interface bus_if;\n logic clk;\n logic sig;\n modport mp (input sig);\nendinterface\n",
)
.expect("write");
std::fs::write(dir.join("sub.sv"), "module sub (bus_if.mp bus);\nendmodule\n").expect("write");
let top = dir.join("top.sv");
let text = "\
module top;
bus_if b_if ();
sub u (.bus(b_if.mp));
endmodule
";
std::fs::write(&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(WIDE_SCOPE),
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")
)),
// Line 1 column 2 is the `bus_if` of the instantiation.
frame(&format!(
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/hover","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":1,"character":2}}}}}}"#
)),
// Line 2 column 19 is the `mp` of `.bus(b_if.mp)`.
frame(&format!(
r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/hover","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":2,"character":19}}}}}}"#
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":4,"method":"textDocument/definition","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":2,"character":19}}}}}}"#
)),
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 response {id} in {messages:#?}"))
};
let iface = response(2)["result"]["contents"]["value"].as_str().expect("hover markdown");
assert!(iface.contains("**interface**"), "not \"module\" any more: got {iface}");
assert!(iface.contains("bus_if.sv:1"), "got {iface}");
let modport = response(3)["result"]["contents"]["value"].as_str().expect("hover markdown");
assert!(modport.contains("**modport**"), "got {modport}");
assert!(modport.contains("modport mp (input sig)"), "its own line: got {modport}");
let definition = &response(4)["result"];
let target = definition.get("uri").map_or(&definition[0], |_| definition);
assert!(
target["uri"].as_str().expect("a uri").ends_with("bus_if.sv"),
"the jump lands on the modport declaration: {definition:#?}"
);
assert_eq!(target["range"]["start"]["line"], 3);
let _ = std::fs::remove_dir_all(&dir);
}
/// An interface signal is named three more ways than a module's ever was — in
/// a modport's port list, in a clocking block, and through a `virtual` handle
/// in another file. Renaming the declaration must rewrite all of them, and
/// hovering the cross-file use must find the declaration's own line.
#[test]
fn renaming_an_interface_signal_rewrites_its_modport_clocking_and_a_handle_use() {
let dir = temp_dir("ifacerename");
let iface = dir.join("bus_if.sv");
let iface_text = "\
interface bus_if;
logic clk;
logic sig;
modport mp (input sig);
clocking cb @(posedge clk);
input sig;
endclocking
endinterface
";
std::fs::write(&iface, iface_text).expect("write");
let env = dir.join("env.sv");
let env_text = "\
class env;
virtual bus_if vif;
task go ();
x = vif.sig;
endtask
endclass
";
std::fs::write(&env, env_text).expect("write");
let root = format!("file://{}", dir.display());
let iface_uri = format!("file://{}", iface.display());
let env_uri = format!("file://{}", env.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(WIDE_SCOPE),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{iface_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string(iface_text).expect("json")
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{env_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string(env_text).expect("json")
)),
// `vif.sig` in the other file — line 3, column 12.
frame(&format!(
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/hover","params":{{"textDocument":{{"uri":"{env_uri}"}},"position":{{"line":3,"character":12}}}}}}"#
)),
// The signal's own declaration — line 2, column 8.
frame(&format!(
r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/rename","params":{{"textDocument":{{"uri":"{iface_uri}"}},"position":{{"line":2,"character":8}},"newName":"s2"}}}}"#
)),
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 response {id} in {messages:#?}"))
};
let hover = response(2)["result"]["contents"]["value"].as_str().expect("hover markdown");
assert!(hover.contains("bus_if.sv:3"), "the declaration's own file and line: got {hover}");
assert!(hover.contains("logic sig"), "got {hover}");
let changes = &response(3)["result"]["changes"];
let own = changes[&iface_uri].as_array().expect("edits for the interface");
let lines: Vec<i64> = own.iter().filter_map(|e| e["range"]["start"]["line"].as_i64()).collect();
assert!(own.iter().all(|e| e["newText"] == "s2"), "{own:#?}");
assert!(
lines.contains(&2) && lines.contains(&3) && lines.contains(&5),
"declaration, modport list and clocking block: {own:#?}"
);
let elsewhere = changes[&env_uri].as_array().expect("edits for the handle's file");
assert_eq!(elsewhere.len(), 1, "{elsewhere:#?}");
assert_eq!(elsewhere[0]["range"]["start"]["line"], 3);
assert_eq!(elsewhere[0]["range"]["start"]["character"], 12);
let _ = std::fs::remove_dir_all(&dir);
}
// ----------------------------------------------------------------------
// struct-members (TODO.md §17)
// ----------------------------------------------------------------------
/// The generated-register-package shape, which is what the whole round is
/// for: `reg2hw.ctrl.tx.q` in one file, typed by a `typedef struct packed`
/// four links away in another — with the two inner links written as **inline**
/// aggregates that have no type name at all. Hover names the declaring file
/// and line, and F12 lands on it.
#[test]
fn a_register_packages_nested_struct_field_is_hovered_and_navigated_across_files() {
let dir = temp_dir("structreg");
let pkg = dir.join("uart_reg_pkg.sv");
let pkg_text = "\
package uart_reg_pkg;
typedef struct packed {
struct packed {
logic q;
} tx;
} uart_reg2hw_ctrl_reg_t;
typedef struct packed {
uart_reg2hw_ctrl_reg_t ctrl;
} uart_reg2hw_t;
endpackage
";
std::fs::write(&pkg, pkg_text).expect("write");
let core = dir.join("uart_core.sv");
let text = "\
module uart_core (
input uart_reg_pkg::uart_reg2hw_t reg2hw
);
assign tx_enable = reg2hw.ctrl.tx.q;
endmodule
";
std::fs::write(&core, text).expect("write");
let root = format!("file://{}", dir.display());
let uri = format!("file://{}", core.display());
// Line 3 is ` assign tx_enable = reg2hw.ctrl.tx.q;`: `ctrl` at column 28,
// `tx` at 33, the tail `q` at 36.
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(WIDE_SCOPE),
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")
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/hover","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":3,"character":36}}}}}}"#
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/definition","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":3,"character":36}}}}}}"#
)),
// The middle links answer too, each in the struct that declares it.
frame(&format!(
r#"{{"jsonrpc":"2.0","id":4,"method":"textDocument/hover","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":3,"character":33}}}}}}"#
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":5,"method":"textDocument/hover","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":3,"character":28}}}}}}"#
)),
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 response {id} in {messages:#?}"))
};
let hover = response(2)["result"]["contents"]["value"].as_str().expect("hover markdown");
assert!(hover.contains("uart_reg_pkg.sv:4"), "the field's own file and line: got {hover}");
assert!(hover.contains("logic q"), "the declaration's own line: got {hover}");
assert!(hover.contains("**struct member**"), "labelled as what it is: got {hover}");
let definition = &response(3)["result"];
let target = definition.get("uri").map_or(&definition[0], |_| definition);
assert!(
target["uri"].as_str().expect("a uri").ends_with("uart_reg_pkg.sv"),
"the jump follows the hover: {definition:#?}"
);
assert_eq!(target["range"]["start"]["line"], 3, "{definition:#?}");
let tx = response(4)["result"]["contents"]["value"].as_str().expect("hover markdown");
assert!(tx.contains("uart_reg_pkg.sv:5"), "the inline aggregate member: got {tx}");
let ctrl = response(5)["result"]["contents"]["value"].as_str().expect("hover markdown");
assert!(ctrl.contains("uart_reg_pkg.sv:9"), "the named-type member: got {ctrl}");
let _ = std::fs::remove_dir_all(&dir);
}
/// Renaming a struct field from its own declaration rewrites the `s.field`
/// uses in other files — the edit set that used to hold only the declaration,
/// because nothing recorded the use.
#[test]
fn a_struct_field_is_renamed_with_its_uses_in_another_file() {
let dir = temp_dir("structrename");
let bus = dir.join("bus_pkg.sv");
let bus_text = "\
package bus_pkg;
typedef struct packed {
logic [7:0] addr;
} bus_t;
endpackage
";
std::fs::write(&bus, bus_text).expect("write");
let top = dir.join("top.sv");
let text = "\
module top;
bus_pkg::bus_t s;
assign w = s.addr;
endmodule
";
std::fs::write(&top, text).expect("write");
let root = format!("file://{}", dir.display());
let bus_uri = format!("file://{}", bus.display());
let top_uri = format!("file://{}", top.display());
// `addr` is declared at line 2 column 16 of the package, and used at line
// 2 column 15 of `top.sv`.
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(WIDE_SCOPE),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{bus_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string(bus_text).expect("json")
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/references","params":{{"textDocument":{{"uri":"{bus_uri}"}},"position":{{"line":2,"character":16}},"context":{{"includeDeclaration":false}}}}}}"#
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/rename","params":{{"textDocument":{{"uri":"{bus_uri}"}},"position":{{"line":2,"character":16}},"newName":"address"}}}}"#
)),
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 response {id} in {messages:#?}"))
};
let references = response(2)["result"].as_array().expect("a list");
assert_eq!(references.len(), 1, "the cross-file use: {references:#?}");
assert!(references[0]["uri"].as_str().expect("a uri").ends_with("top.sv"));
assert_eq!(references[0]["range"]["start"]["line"], 2);
let changes = &response(3)["result"]["changes"];
let own = changes[&bus_uri].as_array().expect("edits for the package");
assert_eq!(own.len(), 1, "{own:#?}");
assert_eq!(own[0]["range"]["start"]["line"], 2);
let elsewhere = changes[&top_uri].as_array().expect("edits for the using file");
assert_eq!(elsewhere.len(), 1, "{elsewhere:#?}");
assert_eq!(elsewhere[0]["range"]["start"]["line"], 2);
assert_eq!(elsewhere[0]["range"]["start"]["character"], 15);
assert!(elsewhere.iter().all(|e| e["newText"] == "address"), "{elsewhere:#?}");
let _ = std::fs::remove_dir_all(&dir);
}
/// **The member list over the wire** (2026-09-02): the two trigger characters
/// are advertised, a `.` request carrying the client's `context` answers with
/// members and nothing else, a `::` request answers a package's members, and
/// an ordinary identifier request is untouched by either.
///
/// See `docs/features/member-completion/README.md`.
#[test]
fn member_completion_round_trips_over_the_wire() {
let dir = temp_dir("members");
let base = dir.join("member_base.sv");
std::fs::write(&base, "class member_base_c;\n bit inherited_field;\nendclass\n")
.expect("write");
let pkg = dir.join("member_pkg.sv");
std::fs::write(
&pkg,
"package member_pkg;\n localparam int MEMBER_W = 8;\n typedef struct packed { logic a; } member_cfg_t;\nendpackage\n",
)
.expect("write");
let top_text = "class member_item_c extends member_base_c;\n bit own_field;\nendclass\nmodule member_top;\n member_item_c item;\n initial begin\n item.\n end\nendmodule\n";
let top = dir.join("member_top.sv");
std::fs::write(&top, top_text).expect("write");
let root = format!("file://{}", dir.display());
let top_uri = format!("file://{}", top.display());
// `member_pkg::` on the same line the dot request used, so both are asked
// of a buffer the server has really been told about.
let scoped = "class member_item_c extends member_base_c;\n bit own_field;\nendclass\nmodule member_top;\n member_item_c item;\n initial begin\n $display(member_pkg::);\n end\nendmodule\n";
// And a plain identifier, to show the six tiers still answer as they did.
let plain = "module member_top;\n logic member_sig;\n assign x = member_s\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":"{top_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string(top_text).expect("json")
)),
// The cursor right after the `.` of ` item.` on line 6, asked the
// way VS Code asks it: triggerKind 2, triggerCharacter ".".
frame(&format!(
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/completion","params":{{"textDocument":{{"uri":"{top_uri}"}},"position":{{"line":6,"character":9}},"context":{{"triggerKind":2,"triggerCharacter":"."}}}}}}"#
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didChange","params":{{"textDocument":{{"uri":"{top_uri}","version":2}},"contentChanges":[{{"text":{}}}]}}}}"#,
serde_json::to_string(scoped).expect("json")
)),
// Right after the `::` of `member_pkg::` on line 6.
frame(&format!(
r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/completion","params":{{"textDocument":{{"uri":"{top_uri}"}},"position":{{"line":6,"character":25}},"context":{{"triggerKind":2,"triggerCharacter":":"}}}}}}"#
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didChange","params":{{"textDocument":{{"uri":"{top_uri}","version":3}},"contentChanges":[{{"text":{}}}]}}}}"#,
serde_json::to_string(plain).expect("json")
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":4,"method":"textDocument/completion","params":{{"textDocument":{{"uri":"{top_uri}"}},"position":{{"line":2,"character":21}}}}}}"#
)),
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 response {id} in {messages:#?}"))
};
let labels = |id: u32| -> Vec<String> {
let mut names: Vec<String> = response(id)["result"]["items"]
.as_array()
.unwrap_or_else(|| panic!("no completion list in {:#?}", response(id)))
.iter()
.map(|item| item["label"].as_str().unwrap_or_default().to_string())
.collect();
names.sort();
names
};
// 1. The two separators are advertised, because a member list has no
// identifier of its own to be asked for.
let capabilities = &response(1)["result"]["capabilities"];
let triggers = capabilities["completionProvider"]["triggerCharacters"]
.as_array()
.unwrap_or_else(|| panic!("no completion triggers in {capabilities:#?}"));
assert_eq!(triggers, &[".", ":"]);
// 2. `item.` — the class's own member and the base's, from another file,
// and nothing else at all.
assert_eq!(labels(2), vec!["inherited_field", "own_field"]);
let items = response(2)["result"]["items"].as_array().expect("a list");
for item in items {
assert!(
item["sortText"].as_str().is_some_and(|s| s.starts_with('0')),
"every item is a member: {item:#?}"
);
let edit = &item["textEdit"];
assert_eq!(edit["range"]["start"], edit["range"]["end"], "an empty range at the cursor");
assert_eq!(edit["newText"], item["label"]);
}
assert_eq!(response(2)["result"]["isIncomplete"], false, "the whole list is the answer");
// 3. `member_pkg::` — the package's members, out of the index.
assert_eq!(labels(3), vec!["MEMBER_W", "member_cfg_t"]);
// 4. And an ordinary identifier still gets the tiered answer it always
// did: its own scope, plus keywords or project words below it.
let plain_labels = labels(4);
assert!(plain_labels.contains(&"member_sig".to_string()), "{plain_labels:#?}");
let plain_items = response(4)["result"]["items"].as_array().expect("a list");
assert!(
plain_items.iter().any(|i| i["sortText"].as_str().is_some_and(|s| !s.starts_with('0'))),
"the tiers below 0 answer at a plain identifier: {plain_items:#?}"
);
let _ = std::fs::remove_dir_all(&dir);
}
/// **The connection list over the wire** (2026-09-02 rework): a `.` typed
/// inside an instantiation's port map lists the module's ports and nothing
/// else, with the `.` trigger character the client really sends. This is the
/// commonest completion position in RTL and the one the round would otherwise
/// have turned into silence.
#[test]
fn a_connection_list_completes_ports_over_the_wire() {
let dir = temp_dir("ports");
let sub = dir.join("wire_sub.sv");
std::fs::write(
&sub,
"module wire_sub #(\n parameter int WIRE_W = 8\n) (\n input logic clk,\n input logic [WIRE_W-1:0] data,\n output logic ready\n);\nendmodule\n",
)
.expect("write");
let top_text = "module wire_top;\n wire_sub u_sub (\n .\n );\nendmodule\n";
let top = dir.join("wire_top.sv");
std::fs::write(&top, top_text).expect("write");
let root = format!("file://{}", dir.display());
let top_uri = format!("file://{}", top.display());
// The same buffer with the first port already connected, to show the
// list shrinks rather than repeating itself.
let partly = "module wire_top;\n wire_sub u_sub (\n .clk(clk),\n .\n );\nendmodule\n";
// …and a parameter override, which lists parameters instead.
let params = "module wire_top;\n wire_sub #(.) u_sub ();\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":"{top_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string(top_text).expect("json")
)),
// Right after the `.` on line 2, asked the way VS Code asks it.
frame(&format!(
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/completion","params":{{"textDocument":{{"uri":"{top_uri}"}},"position":{{"line":2,"character":5}},"context":{{"triggerKind":2,"triggerCharacter":"."}}}}}}"#
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didChange","params":{{"textDocument":{{"uri":"{top_uri}","version":2}},"contentChanges":[{{"text":{}}}]}}}}"#,
serde_json::to_string(partly).expect("json")
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/completion","params":{{"textDocument":{{"uri":"{top_uri}"}},"position":{{"line":3,"character":5}},"context":{{"triggerKind":2,"triggerCharacter":"."}}}}}}"#
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didChange","params":{{"textDocument":{{"uri":"{top_uri}","version":3}},"contentChanges":[{{"text":{}}}]}}}}"#,
serde_json::to_string(params).expect("json")
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":4,"method":"textDocument/completion","params":{{"textDocument":{{"uri":"{top_uri}"}},"position":{{"line":1,"character":14}},"context":{{"triggerKind":2,"triggerCharacter":"."}}}}}}"#
)),
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 response {id} in {messages:#?}"))
};
let labels = |id: u32| -> Vec<String> {
let mut names: Vec<String> = response(id)["result"]["items"]
.as_array()
.unwrap_or_else(|| panic!("no completion list in {:#?}", response(id)))
.iter()
.map(|item| item["label"].as_str().unwrap_or_default().to_string())
.collect();
names.sort();
names
};
// The ports of the module in the other file, and nothing else — no
// keyword, no project word, no 512-item dump.
assert_eq!(labels(2), vec!["clk", "data", "ready"]);
let items = response(2)["result"]["items"].as_array().expect("a list");
for item in items {
assert!(
item["sortText"].as_str().is_some_and(|s| s.starts_with('0')),
"every item is a port: {item:#?}"
);
assert_eq!(item["kind"], 5, "CompletionItemKind.Field");
assert_eq!(item["textEdit"]["newText"], item["label"], "the bare name");
let edit = &item["textEdit"];
assert_eq!(edit["range"]["start"], edit["range"]["end"], "an empty range at the cursor");
}
// A port already connected is not offered again.
assert_eq!(labels(3), vec!["data", "ready"]);
// And `#(.` lists the parameters instead.
assert_eq!(labels(4), vec!["WIRE_W"]);
let _ = std::fs::remove_dir_all(&dir);
}
// ----------------------------------------------------------------------
// constraint-bodies (TODO.md §20)
// ----------------------------------------------------------------------
/// The gap `docs/coverage_gaps.md` C1 named: renaming a `rand` property used
/// inside a `constraint` left the constraint untouched. One session pins the
/// whole chain over the wire — hover on a property inside a body, definition
/// from inside a `randomize() with` block, and a rename whose edit set
/// includes the constraint use and still formats.
#[test]
fn renaming_a_rand_field_rewrites_its_constraint_uses() {
let dir = temp_dir("constraintrename");
let file = dir.join("item.sv");
let text = "\
class item;
rand int user_id;
rand int mode;
constraint c_id {
user_id < 5;
solve mode before user_id;
}
task run();
void'(this.randomize() with { user_id == 1; });
endtask
endclass
";
std::fs::write(&file, text).expect("write");
let root = format!("file://{}", dir.display());
let uri = format!("file://{}", file.display());
// Line 1 col 11 is the declaration of `user_id`.
// Line 4 col 4 is its use inside the constraint body.
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(text).expect("json")
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/hover","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":4,"character":6}}}}}}"#
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/definition","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":4,"character":6}}}}}}"#
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":4,"method":"textDocument/rename","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":1,"character":11}},"newName":"uid"}}}}"#
)),
// Hover on the constraint's own name says what it is.
frame(&format!(
r#"{{"jsonrpc":"2.0","id":5,"method":"textDocument/hover","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":3,"character":14}}}}}}"#
)),
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 response {id} in {messages:#?}"))
};
let hover = response(2)["result"]["contents"]["value"].as_str().expect("hover markdown");
assert!(hover.contains("rand int user_id"), "the property's own line: got {hover}");
let definition = &response(3)["result"];
let range = definition.get("range").unwrap_or(&definition[0]["range"]);
assert_eq!(range["start"]["line"], 1, "the property's declaration: {definition:#?}");
let edits = response(4)["result"]["changes"][&uri].as_array().expect("edits");
let lines: Vec<i64> =
edits.iter().filter_map(|e| e["range"]["start"]["line"].as_i64()).collect();
assert!(edits.iter().all(|e| e["newText"] == "uid"), "{edits:#?}");
for line in [1, 4, 5, 8] {
assert!(lines.contains(&line), "line {line} must be rewritten: {edits:#?}");
}
// Apply the edits and check the result still parses and formats — the
// rename must not have produced something the formatter refuses.
let mut renamed = text.to_string();
let mut spans: Vec<(usize, usize)> = Vec::new();
for (i, line) in text.lines().enumerate() {
for edit in edits {
if edit["range"]["start"]["line"].as_i64() == Some(i as i64) {
let start_col = edit["range"]["start"]["character"].as_u64().expect("col") as usize;
let end_col = edit["range"]["end"]["character"].as_u64().expect("col") as usize;
let line_start: usize = text.lines().take(i).map(|l| l.len() + 1).sum::<usize>();
spans.push((line_start + start_col, line_start + end_col));
}
}
let _ = line;
}
spans.sort_unstable();
for (start, end) in spans.into_iter().rev() {
renamed.replace_range(start..end, "uid");
}
assert!(!renamed.contains("user_id"), "every occurrence was rewritten:\n{renamed}");
let formatted = vlog_formatter::format_source(&renamed, &vlog_formatter::Config::default())
.expect("the renamed file still formats");
assert!(formatted.contains("uid < 5;"), "the constraint body kept the new name:\n{formatted}");
let constraint_hover =
response(5)["result"]["contents"]["value"].as_str().expect("hover markdown");
assert!(constraint_hover.contains("**constraint**"), "got {constraint_hover}");
let _ = std::fs::remove_dir_all(&dir);
}
/// The cross-file half: the class is in one file, its out-of-block
/// constraint in another. Definition from inside the body reaches the
/// property, and renaming **from the declaration** rewrites the constraint
/// too. The other direction — renaming from inside the body — is refused,
/// and that refusal is `vlog_refactor`'s and predates this round: an
/// out-of-body `task item::show()` gets the same one for the same reason
/// (see the feature README's Handshakes).
#[test]
fn renaming_a_rand_field_reaches_a_constraint_in_another_file() {
let dir = temp_dir("constraintrenamecross");
let decl = dir.join("item.sv");
std::fs::write(
&decl,
"class item;\n rand int user_id;\n extern constraint c_id;\nendclass\n",
)
.expect("write");
let cons = dir.join("cons.sv");
std::fs::write(&cons, "constraint item::c_id {\n user_id < 5;\n}\n").expect("write");
let root = format!("file://{}", dir.display());
let decl_uri = format!("file://{}", decl.display());
let cons_uri = format!("file://{}", cons.display());
let cons_text = std::fs::read_to_string(&cons).expect("read");
let decl_text = std::fs::read_to_string(&decl).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":{}}"#),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{cons_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string(&cons_text).expect("json")
)),
// Definition from inside the out-of-block constraint body.
frame(&format!(
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/definition","params":{{"textDocument":{{"uri":"{cons_uri}"}},"position":{{"line":1,"character":4}}}}}}"#
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{decl_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string(&decl_text).expect("json")
)),
// Rename from the declaration: both files must be edited.
frame(&format!(
r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/rename","params":{{"textDocument":{{"uri":"{decl_uri}"}},"position":{{"line":1,"character":13}},"newName":"uid"}}}}"#
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":4,"method":"textDocument/references","params":{{"textDocument":{{"uri":"{decl_uri}"}},"position":{{"line":1,"character":13}},"context":{{"includeDeclaration":false}}}}}}"#
)),
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 response {id} in {messages:#?}"))
};
let definition = &response(2)["result"];
let target = definition
.get("uri")
.or_else(|| definition[0].get("uri"))
.and_then(|u| u.as_str())
.unwrap_or_default();
assert_eq!(target, decl_uri, "the property in the other file: {definition:#?}");
let changes = &response(3)["result"]["changes"];
assert!(!changes[&decl_uri].is_null(), "the declaring file is edited: {changes:#?}");
let in_constraint = changes[&cons_uri].as_array().expect("the constraint file is edited");
assert_eq!(in_constraint.len(), 1, "{in_constraint:#?}");
assert_eq!(in_constraint[0]["newText"], "uid");
assert_eq!(in_constraint[0]["range"]["start"]["line"], 1, "inside the body");
// The same occurrence is what `references` reports, from the other file.
let references = response(4)["result"].as_array().expect("a list");
assert_eq!(references.len(), 1, "{references:#?}");
assert_eq!(references[0]["uri"], cons_uri);
let _ = std::fs::remove_dir_all(&dir);
}
/// TODO.md §21 round 2: a `rand` field sampled by a coverpoint is renamed
/// from its declaration, hover inside a bin expression says what the name is,
/// and `cg.cp` reaches the coverpoint the covergroup declares.
#[test]
fn renaming_a_rand_field_rewrites_its_coverpoint_uses() {
let dir = temp_dir("covergrouprename");
let file = dir.join("cov.sv");
let text = "\
class item;
rand int user_id;
int limit;
covergroup cg_id;
cp_id: coverpoint user_id {
bins low = {[0:limit]};
}
cr: cross cp_id, user_id;
endgroup
endclass
";
std::fs::write(&file, text).expect("write");
let root = format!("file://{}", dir.display());
let uri = format!("file://{}", file.display());
// Line 1 col 11 is the declaration of `user_id`.
// Line 4 col 22 is its use as the sampled expression.
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(text).expect("json")
)),
// Hover inside the bin expression.
frame(&format!(
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/hover","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":5,"character":21}}}}}}"#
)),
// Definition from the sampled expression.
frame(&format!(
r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/definition","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":4,"character":24}}}}}}"#
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":4,"method":"textDocument/rename","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":1,"character":11}},"newName":"uid"}}}}"#
)),
// Hover on the covergroup's own name, and on a coverpoint label.
frame(&format!(
r#"{{"jsonrpc":"2.0","id":5,"method":"textDocument/hover","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":3,"character":14}}}}}}"#
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":6,"method":"textDocument/hover","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":4,"character":6}}}}}}"#
)),
// The cross operand reaches the coverpoint the covergroup declared.
frame(&format!(
r#"{{"jsonrpc":"2.0","id":7,"method":"textDocument/definition","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":7,"character":14}}}}}}"#
)),
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 response {id} in {messages:#?}"))
};
let hover = response(2)["result"]["contents"]["value"].as_str().expect("hover markdown");
assert!(hover.contains("int limit"), "the bin expression's name: got {hover}");
let definition = &response(3)["result"];
let range = definition.get("range").unwrap_or(&definition[0]["range"]);
assert_eq!(range["start"]["line"], 1, "the property's declaration: {definition:#?}");
let edits = response(4)["result"]["changes"][&uri].as_array().expect("edits");
let lines: Vec<i64> =
edits.iter().filter_map(|e| e["range"]["start"]["line"].as_i64()).collect();
assert!(edits.iter().all(|e| e["newText"] == "uid"), "{edits:#?}");
for line in [1, 4, 7] {
assert!(lines.contains(&line), "line {line} must be rewritten: {edits:#?}");
}
let covergroup_hover =
response(5)["result"]["contents"]["value"].as_str().expect("hover markdown");
assert!(covergroup_hover.contains("**covergroup**"), "got {covergroup_hover}");
let coverpoint_hover =
response(6)["result"]["contents"]["value"].as_str().expect("hover markdown");
assert!(coverpoint_hover.contains("**coverpoint**"), "got {coverpoint_hover}");
let cross_operand = &response(7)["result"];
let range = cross_operand.get("range").unwrap_or(&cross_operand[0]["range"]);
assert_eq!(range["start"]["line"], 4, "the coverpoint's label: {cross_operand:#?}");
let _ = std::fs::remove_dir_all(&dir);
}
/// The cross-file half: the class is in one file, and a covergroup in another
/// class samples a property it inherits from it. Definition from the sampled
/// expression reaches the base class's property, and renaming from that
/// declaration rewrites the coverpoint too.
#[test]
fn renaming_a_rand_field_reaches_a_coverpoint_in_another_file() {
let dir = temp_dir("covergrouprenamecross");
let decl = dir.join("base.sv");
std::fs::write(
&decl,
"package base_pkg;\n class base_item;\n rand int user_id;\n endclass\nendpackage\n",
)
.expect("write");
let cov = dir.join("cov.sv");
std::fs::write(
&cov,
"class my_item extends base_pkg::base_item;\n covergroup cg;\n cp: coverpoint user_id;\n endgroup\nendclass\n",
)
.expect("write");
let root = format!("file://{}", dir.display());
let decl_uri = format!("file://{}", decl.display());
let cov_uri = format!("file://{}", cov.display());
let cov_text = std::fs::read_to_string(&cov).expect("read");
let decl_text = std::fs::read_to_string(&decl).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":{}}"#),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{cov_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string(&cov_text).expect("json")
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/definition","params":{{"textDocument":{{"uri":"{cov_uri}"}},"position":{{"line":2,"character":20}}}}}}"#
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{decl_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string(&decl_text).expect("json")
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/rename","params":{{"textDocument":{{"uri":"{decl_uri}"}},"position":{{"line":2,"character":13}},"newName":"uid"}}}}"#
)),
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 response {id} in {messages:#?}"))
};
let definition = &response(2)["result"];
let target = definition
.get("uri")
.or_else(|| definition[0].get("uri"))
.and_then(|u| u.as_str())
.unwrap_or_default();
assert_eq!(target, decl_uri, "the base class's property: {definition:#?}");
let changes = &response(3)["result"]["changes"];
assert!(!changes[&decl_uri].is_null(), "the declaring file is edited: {changes:#?}");
let in_cov = changes[&cov_uri].as_array().expect("the covergroup file is edited");
assert_eq!(in_cov.len(), 1, "{in_cov:#?}");
assert_eq!(in_cov[0]["newText"], "uid");
assert_eq!(in_cov[0]["range"]["start"]["line"], 2, "inside the coverpoint");
let _ = std::fs::remove_dir_all(&dir);
}