New pairs.rs: a stack matcher over the token stream for begin/end and 16 relative pairs, with guards for every no-body construct that spells an opener keyword (extern/DPI prototypes, typedef class, virtual interface, assert property, covergroup with function sample, ...). Non-cascading mismatch recovery makes one missing end point at the exact unclosed begin. Feeds textDocument/documentHighlight (cursor on begin highlights its matching end) and WARNING diagnostics for unmatched openers/closers — gated on the parse already failing, so macro/ifdef keyword imbalance in working code can never warn. Corpus sweep: 840 clean-parsing files, 11,062 matched pairs, 0 false positives (reproduced independently by QA). Co-Authored-By: Claude Fable 5 <[email protected]>
599 lines
27 KiB
Rust
599 lines
27 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())
|
|
}
|
|
|
|
/// Split a stdout dump into its JSON payloads.
|
|
fn unframe(mut input: impl BufRead) -> Vec<serde_json::Value> {
|
|
let mut out = Vec::new();
|
|
loop {
|
|
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 out;
|
|
}
|
|
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 Some(length) = length else { return out };
|
|
let mut body = vec![0u8; length];
|
|
if input.read_exact(&mut body).is_err() {
|
|
return out;
|
|
}
|
|
match serde_json::from_slice(&body) {
|
|
Ok(value) => out.push(value),
|
|
Err(_) => return out,
|
|
}
|
|
}
|
|
}
|
|
|
|
fn temp_dir(name: &str) -> PathBuf {
|
|
let dir = std::env::temp_dir().join(format!("vfmt_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> {
|
|
let mut child = Command::new(env!("CARGO_BIN_EXE_vfmt-server"))
|
|
.stdin(Stdio::piped())
|
|
.stdout(Stdio::piped())
|
|
.stderr(Stdio::null())
|
|
.spawn()
|
|
.expect("the server binary starts");
|
|
child.stdin.take().expect("stdin").write_all(session.as_bytes()).expect("write session");
|
|
let stdout = child.stdout.take().expect("stdout");
|
|
let messages = unframe(BufReader::new(stdout));
|
|
let status = child.wait().expect("the server exits");
|
|
assert!(status.success(), "clean exit, got {status:?}");
|
|
messages
|
|
}
|
|
|
|
/// An `initialize` + `didOpen` + one `textDocument/formatting` + shutdown
|
|
/// session against a scratch workspace holding `config` as its `vfmt.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_vfmt_toml_governs_formatting_over_the_editors_tab_size() {
|
|
let dir = temp_dir("config");
|
|
std::fs::write(dir.join("vfmt.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_vfmt_toml_warns_once_and_still_formats() {
|
|
let dir = temp_dir("brokenconfig");
|
|
std::fs::write(dir.join("vfmt.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("vfmt.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 vfmt writes it.
|
|
request(3, 4, 0, 4, 9),
|
|
request(4, 0, 0, 99, 0),
|
|
// A cursor on the emoji comment: a leading comment belongs to its
|
|
// item's unit, so the declaration under it is what gets laid out.
|
|
request(5, 1, 8, 1, 8),
|
|
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
|
|
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
|
|
]
|
|
.concat();
|
|
|
|
let messages = talk(&session);
|
|
|
|
let initialize = messages.iter().find(|m| m["id"] == 1).expect("initialize response");
|
|
assert_eq!(
|
|
initialize["result"]["capabilities"]["documentRangeFormattingProvider"],
|
|
serde_json::json!(true),
|
|
"the capability must be advertised now that --lines exists"
|
|
);
|
|
|
|
assert_eq!(
|
|
new_text(&messages, 2),
|
|
"module m;\n // é ✓ 🎉 note\n wire a;\n wire b;\nendmodule\n",
|
|
"only the selected line, and the emoji survives"
|
|
);
|
|
let idle = messages.iter().find(|m| m["id"] == 3).expect("response");
|
|
assert_eq!(idle["result"].as_array().expect("an array").len(), 0, "nothing to change");
|
|
assert_eq!(
|
|
new_text(&messages, 5),
|
|
"module m;\n // é ✓ 🎉 note\n wire a;\n wire b;\nendmodule\n",
|
|
"a leading comment selects the item it belongs to"
|
|
);
|
|
assert_eq!(
|
|
new_text(&messages, 4),
|
|
"module m;\n // é ✓ 🎉 note\n wire a;\n wire b;\nendmodule\n",
|
|
"a range over the whole buffer is a whole-file format"
|
|
);
|
|
|
|
let _ = std::fs::remove_dir_all(&dir);
|
|
}
|
|
|
|
/// A file with a tab (`no-tabs`, Safe fix) and a trailing space
|
|
/// (`no-trailing-whitespace`, Safe fix) — and a name matching its module, so
|
|
/// `module-filename` stays quiet and every finding here is fixable.
|
|
const VIOLATING: &str = "module lint_me;\n\twire a;\n wire b; \nendmodule\n";
|
|
|
|
#[test]
|
|
fn lint_diagnostics_and_a_code_action_round_trip_over_the_wire() {
|
|
let dir = temp_dir("lint");
|
|
let file = dir.join("lint_me.sv");
|
|
std::fs::write(&file, VIOLATING).expect("write");
|
|
let root = format!("file://{}", dir.display());
|
|
let uri = format!("file://{}", file.display());
|
|
|
|
let session = [
|
|
frame(&format!(
|
|
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
|
|
)),
|
|
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
|
|
frame(&format!(
|
|
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
|
|
serde_json::to_string(VIOLATING).expect("json")
|
|
)),
|
|
// Every action for the whole file.
|
|
frame(&format!(
|
|
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/codeAction","params":{{"textDocument":{{"uri":"{uri}"}},"range":{{"start":{{"line":0,"character":0}},"end":{{"line":3,"character":0}}}},"context":{{"diagnostics":[]}}}}}}"#
|
|
)),
|
|
// And the fix-on-save request an editor sends: one kind only.
|
|
frame(&format!(
|
|
r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/codeAction","params":{{"textDocument":{{"uri":"{uri}"}},"range":{{"start":{{"line":0,"character":0}},"end":{{"line":3,"character":0}}}},"context":{{"diagnostics":[],"only":["source.fixAll.vfmt"]}}}}}}"#
|
|
)),
|
|
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.vfmt"), "{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"], "vfmt");
|
|
}
|
|
|
|
// 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.vfmt").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// vfmt: off\n\twire a;\n// vfmt: on\n\twire b;\nendmodule\n";
|
|
|
|
/// The `vfmt` 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 vfmt_server` alone may not, and the test says so
|
|
/// and passes rather than failing for a reason that is not about the server.
|
|
fn vfmt_binary() -> Option<PathBuf> {
|
|
let path = Path::new(env!("CARGO_BIN_EXE_vfmt-server")).with_file_name("vfmt");
|
|
path.is_file().then_some(path)
|
|
}
|
|
|
|
#[test]
|
|
fn fix_all_edits_exactly_what_vfmt_check_fix_edits_inside_a_fence() {
|
|
let Some(vfmt) = vfmt_binary() else {
|
|
eprintln!("skipped: the `vfmt` binary is not built next to `vfmt-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.vfmt"]}}}}}}"#
|
|
)),
|
|
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 `vfmt 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(&vfmt)
|
|
.arg("check")
|
|
.arg("--fix")
|
|
.arg(&cli)
|
|
.stdout(Stdio::null())
|
|
.stderr(Stdio::null())
|
|
.status()
|
|
.expect("the vfmt 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"], "vfmt-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"], "vfmt");
|
|
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";
|
|
|
|
#[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 root = format!("file://{}", dir.display());
|
|
let uri = format!("file://{}", 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),
|
|
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:#?}"
|
|
);
|
|
}
|
|
|
|
// 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"], "vfmt");
|
|
assert!(
|
|
diagnostics.iter().any(|d| d["severity"] == 1),
|
|
"the parse error it explains is still there"
|
|
);
|
|
|
|
let _ = std::fs::remove_dir_all(&dir);
|
|
}
|