Inlay hints M8: port and parameter names on ordered lists

textDocument/inlayHint draws ghost portname:/PARAM: labels on positional
connection lists and all-positional #(...) overrides, from the same plan
extraction M4 uses — walked off the parse tree, so nested-call commas
cannot shift positions. Range filtering runs before any definition is
parsed; plans are cached per request (O(distinct modules)); every
uncertainty is silent, including QA's find: an ifdef-carrying port list
unions its arms in the plan, which is right for an editable skeleton and
wrong for a read-only label, so such plans now hint nothing.

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
lucioandClaude Fable 5 committed 2026-08-24 23:24:01 -07:00
1 parent 3c55783e09
commit fa38fd9dec
8 files changed
+1425 -15

No files matched your search

+867
View File
@@ -0,0 +1,867 @@
//! `textDocument/inlayHint` — the port and parameter names an *ordered*
//! connection list leaves unwritten.
//!
//! `u1 (clk, rst_n, data)` says nothing about which port is which; the module's
//! own declaration does. So every positional connection gets a ghost label
//! naming the port it lands on, and every positional `#( ... )` override gets
//! the parameter's name, both read from the same
//! `vlog_refactor::instantiation_plan` the completion and the signature help
//! use. A named connection (`.clk(x)`), a `.*` and an omitted position get
//! nothing: there is nothing there the reader cannot already see.
//!
//! The facts come off the parse tree rather than the token stream — the
//! opposite of `signature.rs`, and for the opposite reason. Signature help
//! answers about a list that is *being typed* and therefore does not parse;
//! hints decorate a file that is being *read*, where the tree already knows
//! which lists are ordered, which positions are empty, and where every
//! expression starts. A buffer that does not parse simply has no hints, which
//! is the right failure for decoration.
//!
//! See `docs/features/inlay-hints/README.md`.
use std::collections::HashMap;
use lsp_types::{InlayHint, InlayHintKind, InlayHintLabel, Range, Uri};
use vlog_parser::ast::{
Connections, Expr, GenBlock, GenElse, Instance, Instantiation, Item, ItemKind, SourceFile,
};
use vlog_parser::TextRange;
use vlog_refactor::InstantiationPlan;
use crate::convert::Positions;
use crate::state::Workspace;
/// The ghost labels for one range of a buffer.
///
/// An instantiation whose module the index does not hold — or holds twice —
/// gets no hints at all: a hint is decoration, and guessing which of two
/// `fifo`s is meant would put a wrong port name on screen with no way for the
/// reader to tell. More connections than the module has ports is the same
/// answer for the extras.
pub fn inlay_hints(ws: &Workspace, uri: &Uri, range: Range) -> Vec<InlayHint> {
let Some(doc) = ws.document(uri) else { return Vec::new() };
let positions = doc.positions();
let mut hints = Hints {
visible: TextRange::new(positions.offset(range.start), positions.offset(range.end)),
positions: &positions,
plans: Plans::new(ws),
out: Vec::new(),
};
for inst in instantiations(&doc.tree) {
hints.paint(&param_sites(inst), Kind::Params, &inst.module);
for instance in &inst.instances {
hints.paint(&port_sites(instance), Kind::Ports, &inst.module);
}
}
hints.out
}
/// One place a hint may go: where it renders, and which entry of the module's
/// list it names.
struct Site {
/// Byte offset of the first character of the connected expression.
offset: u32,
/// Position in the connection list, counting omitted positions.
index: usize,
}
/// Which of an instantiation's two lists a run of sites came from.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Kind {
/// `sub #(8, 16) u ( ... )`
Params,
/// `sub u ( ... )`
Ports,
}
/// The positional entries of `#( ... )`, or nothing when the list is named.
///
/// Unlike a connection list, a parameter override list has no node saying
/// which spelling it is: every entry carries its own name, empty for a
/// positional one. A list mixing the two is illegal, and a mixed list gets no
/// hints at all rather than hints on the positional half — the entry a
/// positional override lands on is exactly what stops being obvious once a
/// name is written somewhere in the same list.
fn param_sites(inst: &Instantiation) -> Vec<Site> {
let Some(params) = &inst.params else { return Vec::new() };
if params.iter().any(|param| !param.name.is_empty()) {
return Vec::new();
}
params
.iter()
.enumerate()
.filter_map(|(index, param)| site(index, param.expr.as_ref()))
.collect()
}
/// The positional connections of one instance, or nothing when the list is
/// named. An instance array (`sub u [3:0] (a, b)`) hints like a single
/// instance: the connections are the module's ports either way.
fn port_sites(instance: &Instance) -> Vec<Site> {
let Connections::Ordered(conns) = &instance.conns else { return Vec::new() };
conns.iter().enumerate().filter_map(|(index, conn)| site(index, conn.expr.as_ref())).collect()
}
/// A site at the start of `expr`, or nothing for an omitted position
/// (`u (a, , c)`), which has no expression to label.
fn site(index: usize, expr: Option<&Expr>) -> Option<Site> {
Some(Site { offset: expr?.span.start, index })
}
/// The answer being built, and everything one list needs to add to it.
struct Hints<'a> {
/// The byte range the client asked about.
visible: TextRange,
positions: &'a Positions<'a>,
plans: Plans<'a>,
out: Vec<InlayHint>,
}
impl Hints<'_> {
/// Add the hints for one list of `module`, if any of it is on screen.
///
/// The plan is fetched only when a site really is in range, which is what
/// makes a scroll cost the visible instantiations and nothing else.
fn paint(&mut self, sites: &[Site], kind: Kind, module: &str) {
let shown: Vec<&Site> = sites.iter().filter(|site| self.on_screen(site.offset)).collect();
if shown.is_empty() {
return;
}
let Some(plan) = self.plans.get(module) else { return };
for site in shown {
let name = match kind {
Kind::Params => plan.params.get(site.index).map(|param| param.name.as_str()),
Kind::Ports => plan.ports.get(site.index).map(|port| port.name.as_str()),
};
// More connections than the module declares: the extras name
// nothing, and inventing a name for them would be a guess.
let Some(name) = name else { continue };
self.out.push(InlayHint {
position: self.positions.position(site.offset),
label: InlayHintLabel::String(format!("{name}:")),
kind: Some(InlayHintKind::PARAMETER),
text_edits: None,
tooltip: None,
padding_left: None,
padding_right: Some(true),
data: None,
});
}
}
/// Whether `offset` falls inside the requested range, its end included.
///
/// `TextRange::contains` excludes the end, which is right for a span of
/// text and wrong for a viewport: the client asks for the visible lines,
/// and a connection starting on the very last byte of them is on screen.
fn on_screen(&self, offset: u32) -> bool {
self.visible.start <= offset && offset <= self.visible.end
}
}
/// The plans this request has already asked for, by module name.
///
/// A plan costs a file read and a parse, and one screen of RTL commonly
/// instantiates the same module several times, so the answer is remembered for
/// the length of the request. Nothing is kept across requests: the defining
/// file can change between two of them, and a stale port name is worse than a
/// second parse.
struct Plans<'w> {
ws: &'w Workspace,
/// `None` records a module the index could not answer for, so the lookup
/// is not retried once per instantiation of it.
cache: HashMap<String, Option<InstantiationPlan>>,
}
impl<'w> Plans<'w> {
fn new(ws: &'w Workspace) -> Plans<'w> {
Plans { ws, cache: HashMap::new() }
}
fn get(&mut self, module: &str) -> Option<&InstantiationPlan> {
if !self.cache.contains_key(module) {
let plan = self.read(module);
self.cache.insert(module.to_string(), plan);
}
self.cache.get(module)?.as_ref()
}
/// The module's declaration, through the index — the same two steps
/// completion and signature help take. Every refusal (unknown module,
/// duplicate declarations, a file that does not parse, a port or
/// parameter list carrying compiler directives) is silent here.
fn read(&self, module: &str) -> Option<InstantiationPlan> {
let path = vlog_refactor::module_definition(self.ws.index(), module).ok()?;
let definition = self.ws.text_of(path)?;
let plan = vlog_refactor::instantiation_plan(module, &definition, None).ok()?;
// `instantiation_plan` unions every `` `ifdef`` arm into one flat,
// declaration-ordered list when a header's port or parameter list
// carries directives (see its own doc comment) — the right answer for
// a skeleton the user edits, and the wrong one for a hint the user
// only reads: no single configuration has all of those entries, so a
// positional hint drawn against the union names the *wrong* port at
// least half the time, silently. `plan.warnings` is exactly the
// signal that happened; treat it like every other uncertainty this
// module already refuses on, rather than the sentence signature help
// would show for it.
plan.warnings.is_empty().then_some(plan)
}
}
// ----------------------------------------------------------------------
// finding the instantiations
// ----------------------------------------------------------------------
/// Every module instantiation in a file, nested ones included.
///
/// Gate primitives are not here: `and (q, a, b)` is an
/// [`ItemKind::GateInstantiation`], its arguments are not connections to named
/// ports, and the language gives them no names to show.
fn instantiations(file: &SourceFile) -> Vec<&Instantiation> {
let mut out = Vec::new();
walk(&file.items, &mut out);
out
}
fn walk<'a>(items: &'a [Item], out: &mut Vec<&'a Instantiation>) {
for item in items {
match &item.kind {
ItemKind::Instantiation(inst) => out.push(inst),
// The instantiation a `bind` carries is an ordinary one, connection
// list and all.
ItemKind::Bind(bind) => out.push(&bind.inst),
ItemKind::Module(module) => walk(&module.items, out),
ItemKind::Package { items, .. } => walk(items, out),
ItemKind::GenerateRegion { items, .. } => walk(items, out),
ItemKind::GenIf(gen_if) => {
block(&gen_if.then, out);
let mut els = gen_if.els.as_deref();
while let Some(branch) = els {
match branch {
GenElse::If(_, nested) => {
block(&nested.then, out);
els = nested.els.as_deref();
}
GenElse::Block(inner) => {
block(inner, out);
els = None;
}
}
}
}
ItemKind::GenFor(gen_for) => block(&gen_for.body, out),
ItemKind::GenCase(gen_case) => {
for arm in &gen_case.items {
block(&arm.body, out);
}
}
_ => {}
}
}
}
fn block<'a>(gen_block: &'a GenBlock, out: &mut Vec<&'a Instantiation>) {
walk(&gen_block.items, out);
}
#[cfg(test)]
mod tests {
use super::*;
use crate::uri::path_to_uri;
use lsp_types::Position;
use std::fs;
use std::path::PathBuf;
const SUB: &str = "\
module sub #(
parameter int WIDTH = 8,
parameter int DEPTH = 16
) (
input logic clk,
input logic rst_n,
input logic [WIDTH-1:0] data
);
endmodule
";
struct Tree {
path: PathBuf,
}
impl Tree {
fn new(name: &str) -> Tree {
let path = std::env::temp_dir()
.join(format!("vfmt_server_inlay_{}_{name}", std::process::id()));
let _ = fs::remove_dir_all(&path);
fs::create_dir_all(&path).expect("temp dir");
Tree { path }
}
fn write(&self, rel: &str, text: &str) -> PathBuf {
let path = self.path.join(rel);
fs::write(&path, text).expect("write");
path
}
}
impl Drop for Tree {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.path);
}
}
/// The whole buffer, as a range.
fn everything() -> Range {
Range {
start: Position { line: 0, character: 0 },
end: Position { line: u32::MAX, character: 0 },
}
}
/// Every hint in `top`, as `(line, character, label)`.
fn hints_of(name: &str, top: &str) -> Vec<(u32, u32, String)> {
hints_in(name, top, everything(), &[("sub.sv", SUB)])
}
/// Every hint in `top` within `range`, against a workspace of `files`.
fn hints_in(
name: &str,
top: &str,
range: Range,
files: &[(&str, &str)],
) -> Vec<(u32, u32, String)> {
let tree = Tree::new(name);
for (rel, text) in files {
tree.write(rel, text);
}
let path = tree.write("top.sv", top);
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
let uri = path_to_uri(&path).expect("uri");
ws.set_document(uri.clone(), top.to_string());
inlay_hints(&ws, &uri, range)
.into_iter()
.map(|hint| {
let InlayHintLabel::String(label) = hint.label else { panic!("a string label") };
(hint.position.line, hint.position.character, label)
})
.collect()
}
/// Just the labels, in order.
fn labels(hints: &[(u32, u32, String)]) -> Vec<&str> {
hints.iter().map(|(_, _, label)| label.as_str()).collect()
}
#[test]
fn an_ordered_connection_list_names_every_port_in_order() {
let top = "module top;\n sub u1 (clk, rst_n, data);\nendmodule\n";
let hints = hints_of("ordered", top);
assert_eq!(
hints,
vec![
(1, 10, "clk:".to_string()),
(1, 15, "rst_n:".to_string()),
(1, 22, "data:".to_string()),
],
"one hint per connection, at the start of its expression"
);
}
#[test]
fn every_hint_is_a_parameter_kind_with_padding_after_it() {
// The two fields a client actually renders with; a hint glued to the
// expression it labels reads as part of the code.
let tree = Tree::new("shape");
tree.write("sub.sv", SUB);
let top = "module top;\n sub u1 (clk);\nendmodule\n";
let path = tree.write("top.sv", top);
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
let uri = path_to_uri(&path).expect("uri");
ws.set_document(uri.clone(), top.to_string());
let hints = inlay_hints(&ws, &uri, everything());
assert_eq!(hints.len(), 1);
assert_eq!(hints[0].kind, Some(InlayHintKind::PARAMETER));
assert_eq!(hints[0].padding_right, Some(true));
assert_eq!(hints[0].padding_left, None);
assert_eq!(hints[0].text_edits, None, "a hint here inserts nothing");
}
#[test]
fn a_named_connection_list_gets_nothing() {
let top = "module top;\n sub u1 (.clk(clk), .rst_n(rst_n));\nendmodule\n";
assert!(hints_of("named", top).is_empty(), "the names are already written");
}
#[test]
fn a_wildcard_connection_gets_nothing() {
let top = "module top;\n sub u1 (.*);\nendmodule\n";
assert!(hints_of("wildcard", top).is_empty());
}
#[test]
fn an_omitted_position_gets_nothing_and_still_counts() {
// `u (a, , c)` connects the *third* port to `c`; the hole has no
// expression to label, and skipping it must not shift `data` onto
// `rst_n`.
let top = "module top;\n sub u1 (clk, , data);\nendmodule\n";
let hints = hints_of("omitted", top);
assert_eq!(labels(&hints), ["clk:", "data:"]);
assert_eq!(hints[1].0, 1, "still on line 1");
}
#[test]
fn an_empty_connection_list_gets_nothing() {
let top = "module top;\n sub u1 ();\nendmodule\n";
assert!(hints_of("empty", top).is_empty());
}
#[test]
fn a_connection_list_mixing_the_two_spellings_is_survived() {
// Illegal SystemVerilog, and typeable. Whichever way the parser
// recovers, what must not happen is a hint on a `.name(...)` entry or
// a panic — so the assertion is on the labels that *can* appear.
for top in [
"module top;\n sub u1 (clk, .rst_n(r));\nendmodule\n",
"module top;\n sub u1 (.clk(c), rst_n);\nendmodule\n",
] {
// Today both come back empty — the first shape stops the item
// parsing at all, the second is a `Connections::Named` — but the
// assertion is deliberately the weaker invariant, so a change in
// the parser's recovery is not a test failure.
let hints = hints_of("mixedconns", top);
assert!(
hints.iter().all(|(_, _, label)| label == "clk:"),
"no hint may land on a named entry: {hints:?}"
);
}
}
#[test]
fn more_connections_than_ports_leaves_the_extras_unlabelled() {
// Never guess: `sub` has three ports, so the fourth and fifth name
// nothing at all.
let top = "module top;\n sub u1 (clk, rst_n, data, extra, more);\nendmodule\n";
assert_eq!(labels(&hints_of("overrun", top)), ["clk:", "rst_n:", "data:"]);
}
#[test]
fn fewer_connections_than_ports_is_fine() {
let top = "module top;\n sub u1 (clk);\nendmodule\n";
assert_eq!(labels(&hints_of("underrun", top)), ["clk:"]);
}
#[test]
fn ordered_parameter_overrides_are_named_too() {
let top = "module top;\n sub #(8, 16) u1 (clk);\nendmodule\n";
let hints = hints_of("params", top);
assert_eq!(
hints,
vec![
(1, 8, "WIDTH:".to_string()),
(1, 11, "DEPTH:".to_string()),
(1, 19, "clk:".to_string()),
],
"the overrides, then the connection"
);
}
#[test]
fn named_parameter_overrides_get_nothing() {
let top = "module top;\n sub #(.WIDTH(8), .DEPTH(16)) u1 (clk);\nendmodule\n";
assert_eq!(labels(&hints_of("namedparams", top)), ["clk:"], "the ports only");
}
#[test]
fn a_parameter_list_mixing_the_two_spellings_gets_nothing() {
// Illegal SystemVerilog, and typeable. The positional half is exactly
// the part whose meaning stops being obvious, so nothing is claimed.
let top = "module top;\n sub #(8, .DEPTH(16)) u1 (clk);\nendmodule\n";
assert_eq!(labels(&hints_of("mixedparams", top)), ["clk:"]);
}
#[test]
fn an_empty_parameter_list_gets_nothing() {
let top = "module top;\n sub #() u1 (clk);\nendmodule\n";
assert_eq!(labels(&hints_of("emptyparams", top)), ["clk:"]);
}
#[test]
fn more_overrides_than_parameters_leaves_the_extras_unlabelled() {
let top = "module top;\n sub #(8, 16, 32) u1 ();\nendmodule\n";
assert_eq!(labels(&hints_of("paramoverrun", top)), ["WIDTH:", "DEPTH:"]);
}
#[test]
fn commas_inside_a_connected_expression_do_not_shift_a_position() {
// The failure a comma-counting implementation makes: `f(a, b)` reads
// as two connections and every later hint is one port too far along.
let top = "module top;\n sub u1 (f(a, b), {x, y}, data[c:d]);\nendmodule\n";
assert_eq!(labels(&hints_of("nested", top)), ["clk:", "rst_n:", "data:"]);
}
#[test]
fn an_unknown_module_gets_nothing() {
let top = "module top;\n nope u1 (a, b, c);\nendmodule\n";
assert!(hints_of("unknown", top).is_empty());
}
#[test]
fn a_module_two_files_declare_gets_nothing() {
// `module_definition` refuses to guess which one; a hint from the
// wrong declaration would be a lie the reader cannot see through.
let top = "module top;\n dup u1 (a, b);\nendmodule\n";
let dup = "module dup (input logic x, input logic y);\nendmodule\n";
let hints = hints_in("ambiguous", top, everything(), &[("a.sv", dup), ("b.sv", dup)]);
assert!(hints.is_empty(), "{hints:?}");
}
#[test]
fn a_gate_primitive_gets_nothing() {
// A gate's arguments are ordered and have no port names at all.
let top = "module top;\n and u1 (q, a, b);\n not u2 (nq, q);\nendmodule\n";
assert!(hints_of("gate", top).is_empty());
}
#[test]
fn an_instance_array_hints_like_a_single_instance() {
let top = "module top;\n sub u1 [3:0] (clk, rst_n, data);\nendmodule\n";
assert_eq!(labels(&hints_of("array", top)), ["clk:", "rst_n:", "data:"]);
}
#[test]
fn every_instance_of_one_declaration_is_hinted() {
// `sub u1 (...), u2 (...);` is one item with two instances.
let top = "module top;\n sub u1 (clk), u2 (rst_n);\nendmodule\n";
assert_eq!(
labels(&hints_of("twoinstances", top)),
["clk:", "clk:"],
"both start at port 0"
);
}
#[test]
fn an_instantiation_inside_a_generate_block_is_reached() {
let top = "\
module top;
generate
for (genvar i = 0; i < 4; i++) begin : g
sub u1 (clk, rst_n, data);
end
endgenerate
endmodule
";
assert_eq!(labels(&hints_of("generate", top)), ["clk:", "rst_n:", "data:"]);
}
#[test]
fn only_the_requested_range_is_hinted() {
let top = "\
module top;
sub u1 (clk);
sub u2 (rst_n);
sub u3 (data);
endmodule
";
let line = |line: u32| Range {
start: Position { line, character: 0 },
end: Position { line, character: 40 },
};
assert_eq!(labels(&hints_in("range", top, line(2), &[("sub.sv", SUB)])), ["clk:"]);
// The middle line only, by its own line number.
let hints = hints_in("range2", top, line(2), &[("sub.sv", SUB)]);
assert_eq!(hints[0].0, 2, "the hint is on the line asked for");
// Two lines at once.
let two = Range {
start: Position { line: 1, character: 0 },
end: Position { line: 2, character: 40 },
};
assert_eq!(labels(&hints_in("range3", top, two, &[("sub.sv", SUB)])), ["clk:", "clk:"]);
// A range covering nothing hintable.
let none = Range {
start: Position { line: 0, character: 0 },
end: Position { line: 0, character: 5 },
};
assert!(hints_in("range4", top, none, &[("sub.sv", SUB)]).is_empty());
}
#[test]
fn a_position_is_utf16_units_on_a_line_carrying_multibyte_text() {
// The hint's column is what the client draws at, so an `é` on the same
// line must not push it two columns right (2 UTF-8 bytes, 1 unit).
let top = "module top;\n sub u1 (/* é 🎉 */ clk); // é\n sub u2 (rst_n);\nendmodule\n";
let hints = hints_of("utf16", top);
// `/* é 🎉 */ ` is 10 characters and 11 UTF-16 units, because `🎉` is a
// surrogate pair; counting bytes would put the hint six columns right.
assert_eq!(hints[0], (1, 21, "clk:".to_string()));
assert_eq!(hints[1], (2, 10, "clk:".to_string()), "the line before it had é and 🎉");
}
#[test]
fn a_buffer_that_does_not_parse_hints_nothing_rather_than_guessing() {
let top = "module top;\n sub u1 (clk, rst_n\n";
assert!(hints_of("broken", top).is_empty());
}
#[test]
fn an_unopened_document_answers_with_no_hints() {
let ws = Workspace::default();
let uri = path_to_uri(std::path::Path::new("/nowhere/top.sv")).expect("uri");
assert!(inlay_hints(&ws, &uri, everything()).is_empty());
}
#[test]
fn a_positional_parameter_override_writes_no_name_of_its_own() {
// The premise `param_sites` rests on, stated as a test: the parser
// spells a positional override as a `Connection` with an empty name.
let text = "module top;\n sub #(8, .DEPTH(16)) u1 ();\nendmodule\n";
let (tree, _) = vlog_parser::parse_source_tolerant(text);
let insts = instantiations(&tree);
let params = insts[0].params.as_ref().expect("a `#( ... )`");
assert_eq!(params[0].name, "", "`8` names nothing");
assert_eq!(params[1].name, "DEPTH", "`.DEPTH(16)` does");
}
// ---- QA regressions (2026-08-24) ----
//
// See the QA log in `docs/features/inlay-hints/README.md` for how each of
// these was found and what it rules out.
#[test]
fn an_ifdef_carrying_declaration_gets_no_hints_rather_than_a_wrong_one() {
// `instantiation_plan` lists every `` `ifdef`` arm's ports in one flat,
// declaration-ordered list (by design — see its own doc comment): here
// that is `[a, b, clk]`, three entries no single configuration ever
// has at once (real shape is `(a, clk)` or `(b, clk)`, never all
// three). Before this fix, `sub u1 (x, y)` was hinted `a: x, b: y` —
// wrong under *both* configurations, since the true second port is
// always `clk`. A hint the reader cannot verify is exactly the case
// the module's own doc comment says must stay silent.
let sub = "\
module sub (
`ifdef CFG_A
input logic a,
`else
input logic b,
`endif
input logic clk
);
endmodule
";
let top = "module top;\n sub u1 (x, y);\nendmodule\n";
assert!(
hints_in("ifdefports", top, everything(), &[("sub.sv", sub)]).is_empty(),
"a port list whose shape depends on the configuration must not be hinted"
);
}
#[test]
fn an_ifdef_carrying_parameter_list_gets_no_hints_either() {
let sub = "\
module sub #(
`ifdef CFG_A
parameter int A = 1,
`else
parameter int B = 2,
`endif
parameter int WIDTH = 8
) (
input logic clk
);
endmodule
";
let top = "module top;\n sub #(4, 8) u1 (clk);\nendmodule\n";
assert_eq!(
labels(&hints_in("ifdefparams", top, everything(), &[("sub.sv", sub)])),
Vec::<&str>::new(),
"the port hint would be safe on its own, but the whole instantiation stays \
silent because the module carries a directive-bearing list at all"
);
}
#[test]
fn a_self_instantiating_module_does_not_crash() {
// `top` here has no port list at all, so there is nothing to hint —
// the point of the test is that walking into the recursive
// instantiation and fetching `top`'s own plan does not loop or panic.
let top = "module top;\n top u1 (clk);\nendmodule\n";
assert!(hints_of("recursive", top).is_empty());
}
#[test]
fn a_comment_nested_inside_a_connected_expression_does_not_shift_utf16_columns() {
// The nested-call test above pins that a comma inside `f(a, b)` is
// not a connection separator; this pins the same for a multi-byte
// comment nested the same way, so the *column* after it is not off
// too. `🎉` is a surrogate pair (2 UTF-16 units) and `é` is one.
let top = "module top;\n sub u1 (f(/* 🎉é */ a, b), rst_n, data);\nendmodule\n";
let hints = hints_of("emojinested", top);
assert_eq!(labels(&hints), ["clk:", "rst_n:", "data:"]);
assert_eq!(hints[1].1, 29, "rst_n follows the nested comment, not the raw byte count");
}
#[test]
fn a_port_whose_width_depends_on_a_parameter_still_hints_by_name_only() {
// The label is just the port's name; a `[WIDTH-1:0]` type that
// depends on an overridden parameter must not be evaluated or crash.
let sub = "\
module psub #(
parameter int WIDTH = 8
) (
input logic [WIDTH-1:0] data
);
endmodule
";
let top = "module top;\n psub #(16) u1 (data_q);\nendmodule\n";
assert_eq!(
labels(&hints_in("paramwidth", top, everything(), &[("psub.sv", sub)])),
["WIDTH:", "data:"]
);
}
#[test]
fn a_non_ansi_header_definition_hints_correctly() {
let sub = "\
module nasub (clk, rst_n, data);
input clk;
input rst_n;
input [7:0] data;
endmodule
";
let top = "module top;\n nasub u1 (c, r, d);\nendmodule\n";
assert_eq!(
labels(&hints_in("nonansi", top, everything(), &[("nasub.sv", sub)])),
["clk:", "rst_n:", "data:"]
);
}
#[test]
fn a_range_starting_mid_instantiation_hints_only_the_visible_connections() {
// The range filter is per-site, not per-instantiation: a viewport
// that starts after `clk,` hints `rst_n` and `data` but not `clk`,
// which is off the top of it.
let top = "module top;\n sub u1 (clk, rst_n, data);\nendmodule\n";
// " sub u1 (clk, rst_n, data);" -- the comma after clk is column 13.
let mid_range = Range {
start: Position { line: 1, character: 13 },
end: Position { line: 1, character: 40 },
};
assert_eq!(
labels(&hints_in("midrange", top, mid_range, &[("sub.sv", SUB)])),
["rst_n:", "data:"]
);
}
#[test]
fn an_open_unsaved_buffer_of_the_defining_file_wins_over_disk() {
// Handshake claim: "a defining file edited between two requests is
// never read from a stale copy." An unsaved `didChange` to the
// defining module, still open in the workspace, must be what a hint
// request in another file reads — not the last-saved disk copy.
let tree = Tree::new("staleness");
let sub_path = tree.write("sub.sv", SUB);
let top = "module top;\n sub u1 (clk, rst_n, data);\nendmodule\n";
let top_path = tree.write("top.sv", top);
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
let sub_uri = path_to_uri(&sub_path).expect("uri");
let top_uri = path_to_uri(&top_path).expect("uri");
ws.set_document(top_uri.clone(), top.to_string());
// Renamed in the open buffer only; disk still says `clk`.
ws.set_document(sub_uri, SUB.replace("clk", "clk_renamed"));
let hints = inlay_hints(&ws, &top_uri, everything());
let labels: Vec<String> = hints
.into_iter()
.map(|h| {
let InlayHintLabel::String(s) = h.label else { panic!("string") };
s
})
.collect();
assert_eq!(labels, ["clk_renamed:", "rst_n:", "data:"]);
}
/// Order-of-magnitude perf checks, not run as part of the ordinary suite:
/// timing assertions in a shared CI runner are flaky by nature. Run with
/// `cargo test --release -p vfmt_server --bin vfmt-server qa_perf -- --ignored --nocapture`.
mod qa_perf {
use super::*;
#[test]
#[ignore]
fn forty_distinct_ordered_modules_one_screen() {
// Cheap rebuild of the dev's deleted harness: forty distinct
// ~90-line module definitions, each instantiated once, ordered,
// on one 40-line "screen" (range-scoped request). Measured
// 2026-08-24: 840 hints in ~2.8ms release / this machine — same
// order of magnitude as the README's 12.2ms for the same shape.
let tree = Tree::new("qaperf40");
let mut top = String::from("module top;\n");
for i in 0..40 {
let mut def = format!("module m{i} (\n");
for p in 0..20 {
def.push_str(&format!(" input logic p{p},\n"));
}
def.push_str(" input logic last\n);\n");
for _ in 0..85 {
def.push_str(" // filler line to reach ~90 lines\n");
}
def.push_str("endmodule\n");
tree.write(&format!("m{i}.sv"), &def);
let conns: Vec<String> = (0..20).map(|p| format!("p{p}")).collect();
top.push_str(&format!(" m{i} u{i} ({}, last);\n", conns.join(", ")));
}
top.push_str("endmodule\n");
let path = tree.write("top.sv", &top);
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
let uri = path_to_uri(&path).expect("uri");
ws.set_document(uri.clone(), top.clone());
let screen = Range {
start: Position { line: 0, character: 0 },
end: Position { line: 41, character: 0 },
};
// Warm run (index build etc.) then timed run.
let _ = inlay_hints(&ws, &uri, screen);
let start = std::time::Instant::now();
let hints = inlay_hints(&ws, &uri, screen);
let elapsed = start.elapsed();
eprintln!(
"QA perf: 40 distinct ordered modules, one screen: {} hints in {:?}",
hints.len(),
elapsed
);
assert_eq!(hints.len(), 40 * 21);
}
#[test]
#[ignore]
fn same_module_instantiated_100_times_is_o_distinct_not_o_instances() {
// Measured 2026-08-24: 300 hints in ~163µs release / this
// machine — the plan cache collapses 100 instances of one module
// into a single parse, as the README's Cost section claims.
let tree = Tree::new("qaperf100same");
tree.write("sub.sv", SUB);
let mut top = String::from("module top;\n");
for i in 0..100 {
top.push_str(&format!(" sub u{i} (clk, rst_n, data);\n"));
}
top.push_str("endmodule\n");
let path = tree.write("top.sv", &top);
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
let uri = path_to_uri(&path).expect("uri");
ws.set_document(uri.clone(), top.clone());
let _ = inlay_hints(&ws, &uri, everything());
let start = std::time::Instant::now();
let hints = inlay_hints(&ws, &uri, everything());
let elapsed = start.elapsed();
eprintln!(
"QA perf: same module x100 ordered, whole file: {} hints in {:?}",
hints.len(),
elapsed
);
assert_eq!(hints.len(), 300);
}
}
}
+26 -5
View File
@@ -14,6 +14,7 @@ mod diagnostics;
mod folding;
mod format;
mod hover;
mod inlay;
mod lint;
mod locate;
mod nav;
@@ -35,11 +36,11 @@ use std::path::PathBuf;
use lsp_server::Connection;
use lsp_types::{
CodeActionKind, CodeActionOptions, CodeActionProviderCapability, CompletionOptions,
ExecuteCommandOptions, FoldingRangeProviderCapability, InitializeParams, OneOf,
PositionEncodingKind, RenameOptions, SemanticTokensFullOptions, SemanticTokensLegend,
SemanticTokensOptions, SemanticTokensServerCapabilities, ServerCapabilities,
SignatureHelpOptions, TextDocumentSyncCapability, TextDocumentSyncKind,
WorkDoneProgressOptions,
ExecuteCommandOptions, FoldingRangeProviderCapability, InitializeParams, InlayHintOptions,
InlayHintServerCapabilities, OneOf, PositionEncodingKind, RenameOptions,
SemanticTokensFullOptions, SemanticTokensLegend, SemanticTokensOptions,
SemanticTokensServerCapabilities, ServerCapabilities, SignatureHelpOptions,
TextDocumentSyncCapability, TextDocumentSyncKind, WorkDoneProgressOptions,
};
use crate::server::Server;
@@ -134,6 +135,15 @@ fn capabilities() -> ServerCapabilities {
retrigger_characters: None,
work_done_progress_options: WorkDoneProgressOptions::default(),
}),
// Port and parameter names on ordered connection lists. Every hint is
// returned complete — a label, a position and nothing to fetch later —
// so there is no `inlayHint/resolve`.
inlay_hint_provider: Some(OneOf::Right(InlayHintServerCapabilities::Options(
InlayHintOptions {
work_done_progress_options: WorkDoneProgressOptions::default(),
resolve_provider: None,
},
))),
semantic_tokens_provider: Some(SemanticTokensServerCapabilities::SemanticTokensOptions(
SemanticTokensOptions {
work_done_progress_options: WorkDoneProgressOptions::default(),
@@ -210,6 +220,17 @@ mod tests {
assert!(caps.execute_command_provider.is_some());
assert!(caps.completion_provider.is_some());
assert!(caps.signature_help_provider.is_some());
assert!(caps.inlay_hint_provider.is_some());
}
#[test]
fn inlay_hints_resolve_nothing_because_every_hint_is_complete() {
let Some(OneOf::Right(InlayHintServerCapabilities::Options(options))) =
capabilities().inlay_hint_provider
else {
panic!("inlay hints must carry options, not a bare `true`");
};
assert_eq!(options.resolve_provider, None);
}
#[test]
+14 -8
View File
@@ -15,9 +15,9 @@ use lsp_types::notification::{
};
use lsp_types::request::{
CodeActionRequest, Completion, DocumentHighlightRequest, DocumentSymbolRequest, ExecuteCommand,
FoldingRangeRequest, Formatting, GotoDefinition, HoverRequest, PrepareRenameRequest,
RangeFormatting, References, Rename, Request as _, SemanticTokensFullRequest,
SignatureHelpRequest, WorkspaceSymbolRequest,
FoldingRangeRequest, Formatting, GotoDefinition, HoverRequest, InlayHintRequest,
PrepareRenameRequest, RangeFormatting, References, Rename, Request as _,
SemanticTokensFullRequest, SignatureHelpRequest, WorkspaceSymbolRequest,
};
use lsp_types::{
CodeActionKind, CodeActionParams, CompletionParams, DidChangeConfigurationParams,
@@ -25,17 +25,17 @@ use lsp_types::{
DidSaveTextDocumentParams, DocumentFormattingParams, DocumentHighlightParams,
DocumentRangeFormattingParams, DocumentSymbolParams, DocumentSymbolResponse,
ExecuteCommandParams, FoldingRangeParams, GotoDefinitionParams, GotoDefinitionResponse,
HoverParams, LogMessageParams, MessageType, Position, PublishDiagnosticsParams,
ReferenceParams, RenameParams, SemanticTokensParams, SemanticTokensResult, ShowMessageParams,
SignatureHelpParams, TextDocumentPositionParams, Uri, WorkspaceSymbolParams,
WorkspaceSymbolResponse,
HoverParams, InlayHintParams, LogMessageParams, MessageType, Position,
PublishDiagnosticsParams, ReferenceParams, RenameParams, SemanticTokensParams,
SemanticTokensResult, ShowMessageParams, SignatureHelpParams, TextDocumentPositionParams, Uri,
WorkspaceSymbolParams, WorkspaceSymbolResponse,
};
use serde::de::DeserializeOwned;
use serde_json::Value;
use crate::state::Workspace;
use crate::{
code_action, completion, diagnostics, folding, format, hover, nav, pairs, ports, rename,
code_action, completion, diagnostics, folding, format, hover, inlay, nav, pairs, ports, rename,
settings, signature, symbols, tokens,
};
@@ -142,6 +142,12 @@ impl Server {
None => Ok(Value::Null),
}
}),
// Ghost port names on ordered connection lists. Range-scoped, as
// the protocol asks: the client sends the lines it is showing and
// gets the hints inside them.
InlayHintRequest::METHOD => decode(request).and_then(|p: InlayHintParams| {
to_value(inlay::inlay_hints(&self.workspace, &p.text_document.uri, p.range))
}),
SemanticTokensFullRequest::METHOD => {
decode(request).and_then(|p: SemanticTokensParams| {
match self.workspace.document(&p.text_document.uri) {
+103
View File
@@ -1596,3 +1596,106 @@ fn cross_file_references_folding_and_highlights_round_trip_over_the_wire() {
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);
}