Files
lucisv/crates/lucisv_server/src/inlay.rs
T
lucioandClaude Fable 5.1 9604753b6c Lazy codeAction/resolve for the port refactorings, definitions from the index, the inlayHint zero ruled correct
TODO §37 (docs/features/lazy-code-action). Closes the four §10 lines.

37.1 For a client whose resolveSupport lists "edit", the port actions are
offered over the buffer plus the instantiated module's declaration alone
(`ports::offers`, `offer_sources`), carrying `data {uri, position,
title}` and no edit; `codeAction/resolve` (`ports::resolve`) re-runs the
eager path and returns the matching action, matched on the title minus
its count phrase, erroring when the action is gone or the buffer is on
the large-file path. Clients without resolve support get today's eager
answer. Offer flat at ~55 µs from a 3- to a 128-file fan-out where the
eager path was linear; ~4.5 ms vs ~77 ms over the wire on opentitan's
128-file case.

37.2 The inlayHint zero at the default scope is correct: the hinted
module (`pins_if`) is declared outside what the scope reaches, and
definition/hover answer nothing there either. Pinned, not changed.

37.3 `locate::definition_location`: an index-only Location for a closed
file's file-scope declaration from its recorded `DeclPositions`; nav and
workspace symbols routed through it (0.4 µs vs 28 µs). Open buffers keep
the file-read path.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-04 18:15:40 -05:00

928 lines
37 KiB
Rust

//! `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::{Connection, Connections, Expr, Instance, Instantiation, ListElem};
use vlog_parser::TextRange;
use vlog_refactor::InstantiationPlan;
use vlog_semantic::instantiations;
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 site in instantiations::sites(&doc.tree.items) {
let inst = site.inst;
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() };
// A list a tolerant parse recovered inside gets no hints either: which
// parameter a position names is exactly what the skipped text decides, so
// any hint here would be a guess, and a wrong hint is worse than none.
if params.iter().any(ListElem::is_error) {
return Vec::new();
}
let params: Vec<&Connection> = params.iter().filter_map(ListElem::ok).collect();
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() };
// As in `param_sites`: a recovered list's positions are a guess.
if conns.iter().any(ListElem::is_error) {
return Vec::new();
}
conns
.iter()
.filter_map(ListElem::ok)
.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)
}
}
#[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!("lucisv_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_whole_workspace(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_whole_workspace(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 🎉");
}
/// A buffer mid-edit still hints where the *positions* are known, and
/// stops where they are not.
///
/// Header recovery (TODO §32) changed the first half: `sub u1 (clk, rst_n`
/// used to fail to parse at all, so there was nothing to hint from. Now
/// the instantiation survives with both positional connections, and both
/// are at the index they were written at, so both are hinted. The second
/// half is the rule that replaces "does not parse": a list the parser
/// *recovered* inside holds text nobody can index, so `port_sites` and
/// `param_sites` decline the whole list rather than mislabel what follows
/// the hole.
#[test]
fn a_truncated_list_hints_and_a_recovered_one_does_not() {
let top = "module top;\n sub u1 (clk, rst_n\n";
assert_eq!(labels(&hints_of("truncated", top)), ["clk:", "rst_n:"]);
let holed = "module top;\n sub u1 (clk, .\n wire w;\nendmodule\n";
assert!(hints_of("recovered", holed).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::sites(&tree.items);
let params = insts[0].inst.params.as_ref().expect("a `#( ... )`");
let params: Vec<_> = params.iter().filter_map(ListElem::ok).collect();
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_whole_workspace(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:"]);
}
// ------------------------------------------------------------------
// the default scope (TODO §37.2 / `performance_take2.md` §4b, §8)
// ------------------------------------------------------------------
/// An opentitan-shaped tree: an IP block with its RTL and its testbench,
/// and a shared library folder outside that block. Opening
/// `ip/aes/dv/tb/tb.sv` at the shipped `scopeDepth` of 2 raises to
/// `ip/aes`, so `ip/aes/rtl/sub.sv` is indexed and `dv/common/far.sv` is
/// not — which is exactly the shape `hw/ip/aes/dv/tb/tb.sv` has against
/// `hw/dv/sv/common_ifs/pins_if.sv`.
fn default_scoped(name: &str) -> (Tree, Workspace, Uri, &'static str) {
const TB: &str =
"module tb;\n sub u_sub (clk, rst_n, data);\n far u_far (a);\nendmodule\n";
let tree = Tree::new(name);
fs::create_dir_all(tree.path.join("ip/aes/rtl")).expect("dirs");
fs::create_dir_all(tree.path.join("ip/aes/dv/tb")).expect("dirs");
fs::create_dir_all(tree.path.join("dv/common")).expect("dirs");
tree.write("ip/aes/rtl/sub.sv", SUB);
tree.write("dv/common/far.sv", "module far (\n input logic a\n);\nendmodule\n");
let tb = tree.write("ip/aes/dv/tb/tb.sv", TB);
let mut ws = Workspace::default();
// The shipped default: no `index.scope`, `scopeDepth` 2.
ws.set_client_settings(crate::settings::ClientSettings::default());
ws.adopt_roots(vec![tree.path.clone()]);
let uri = path_to_uri(&tb).expect("uri");
ws.set_document(uri.clone(), TB.to_string());
ws.rebuild_index();
(tree, ws, uri, TB)
}
#[test]
fn the_default_scope_hints_a_module_the_didopen_widen_reached() {
// `performance_take2.md` §4b measured 0 hints at the default scope
// where the workspace scope gives 4, and §8 filed it as a correctness
// gap. It is not one: the hints that scope answers are exactly the
// instantiations whose module the widen reached.
let (tree, ws, uri, _) = default_scoped("default_scope");
assert!(
ws.index().files().iter().any(|f| f.ends_with("sub.sv")),
"the widen reached the block's own RTL: {:?}",
ws.index().files()
);
assert!(
!ws.index().files().iter().any(|f| f.ends_with("far.sv")),
"and not the library folder beside it"
);
let hints = inlay_hints(&ws, &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:", "rst_n:", "data:"], "the in-scope instantiation is hinted");
drop(tree);
}
#[test]
fn an_out_of_scope_module_is_unhinted_exactly_as_it_is_undefined() {
// The other half of the same finding: the `far` instantiation gets no
// hints — and go-to-definition and hover give nothing for it either.
// The zero is the scope's, not this module's; inlay uses the same
// `module_definition` lookup its neighbours do.
let (tree, ws, uri, tb) = default_scoped("out_of_scope");
let hints = inlay_hints(&ws, &uri, everything());
assert!(
hints.iter().all(|hint| hint.position.line != 2),
"nothing on the `far` line: {hints:#?}"
);
let far = tb.find("far u_far").expect("the instantiation") as u32;
assert!(crate::nav::definition(&ws, &uri, far).is_empty(), "nor does F12 answer");
assert!(crate::hover::hover(&ws, &uri, far).is_none(), "nor does hover");
// And the moment the scope reaches it, all three answer.
let mut wide = Workspace::default();
wide.open_whole_workspace(vec![tree.path.clone()]);
wide.set_document(uri.clone(), tb.to_string());
let hints = inlay_hints(&wide, &uri, everything());
assert_eq!(hints.len(), 4, "three ports plus `far`'s one: {hints:#?}");
assert_eq!(crate::nav::definition(&wide, &uri, far).len(), 1);
}
/// 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 lucisv_server --bin lucisv-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_whole_workspace(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_whole_workspace(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);
}
}
}