From fa38fd9dec80d29ae01e39f2f1e0a10eb4600aeb Mon Sep 17 00:00:00 2001 From: Guoliang Chen Date: Mon, 24 Aug 2026 23:24:01 -0700 Subject: [PATCH] Inlay hints M8: port and parameter names on ordered lists MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- TODO.md | 2 +- crates/vfmt_server/src/inlay.rs | 867 ++++++++++++++++++++++++++++ crates/vfmt_server/src/main.rs | 31 +- crates/vfmt_server/src/server.rs | 22 +- crates/vfmt_server/tests/e2e.rs | 103 ++++ docs/features/inlay-hints/README.md | 374 ++++++++++++ docs/features/refactor/README.md | 3 +- docs/features/vfmt-server/README.md | 38 ++ 8 files changed, 1425 insertions(+), 15 deletions(-) create mode 100644 crates/vfmt_server/src/inlay.rs create mode 100644 docs/features/inlay-hints/README.md diff --git a/TODO.md b/TODO.md index 5a84a86..86940a2 100644 --- a/TODO.md +++ b/TODO.md @@ -599,7 +599,7 @@ section only tracks the milestones. - [x] **M7 `references-nav`** — cross-file find-all-references (reuse M2's collection machinery), document highlight, folding ranges from the rainbow's pair data. -- [ ] **M8 `inlay-hints`** — port-name hints on ordered connections and +- [x] **M8 `inlay-hints`** — port-name hints on ordered connections and parameter-name hints on ordered `#(...)` overrides, from the index. - [ ] **M9 `file-watching`** — `workspace/didChangeWatchedFiles` for sources and the filelist; reindex on external changes (git pull, diff --git a/crates/vfmt_server/src/inlay.rs b/crates/vfmt_server/src/inlay.rs new file mode 100644 index 0000000..bbeddfb --- /dev/null +++ b/crates/vfmt_server/src/inlay.rs @@ -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 { + 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(¶m_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 { + 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 { + 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 { + 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, +} + +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>, +} + +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 { + 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 = 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 = (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); + } + } +} diff --git a/crates/vfmt_server/src/main.rs b/crates/vfmt_server/src/main.rs index bf83f28..c45162d 100644 --- a/crates/vfmt_server/src/main.rs +++ b/crates/vfmt_server/src/main.rs @@ -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] diff --git a/crates/vfmt_server/src/server.rs b/crates/vfmt_server/src/server.rs index 4b5eac4..bdae975 100644 --- a/crates/vfmt_server/src/server.rs +++ b/crates/vfmt_server/src/server.rs @@ -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) { diff --git a/crates/vfmt_server/tests/e2e.rs b/crates/vfmt_server/tests/e2e.rs index 92d80ab..775a70c 100644 --- a/crates/vfmt_server/tests/e2e.rs +++ b/crates/vfmt_server/tests/e2e.rs @@ -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); +} diff --git a/docs/features/inlay-hints/README.md b/docs/features/inlay-hints/README.md new file mode 100644 index 0000000..f39248e --- /dev/null +++ b/docs/features/inlay-hints/README.md @@ -0,0 +1,374 @@ +# inlay-hints + +M8 of the refactoring plan (`docs/features/refactor/README.md`): **port-name +hints on ordered connections**. + +## Goal + +An ordered connection list writes the *values* and leaves the *names* to the +reader's memory: `u1 (clk, rst_n, data)` says nothing about which port each +expression lands on, and getting that wrong is one of the classic ways to +break a design without breaking the build. The module's own declaration knows, +and vfmt's workspace index knows where that declaration lives, so +`textDocument/inlayHint` draws each port's name as a ghost label before the +expression it belongs to — `clk:`, `rst_n:`, `data:` — and does the same for a +positional `#( ... )` override against the module's parameters. Nothing is +written into the buffer and nothing new is analyzed: the facts come from the +same `vlog_refactor::instantiation_plan` M4's completion and signature help +already read. + +Hints are decoration. Every uncertainty — a module the index does not hold, a +name two files declare, a connection past the last port, a buffer that does +not parse — answers with *no hint* rather than a guess or an error. A wrong +port name drawn in ghost text is worse than no port name, because the reader +has no way to tell it is wrong. + +## Assumptions + +- **The parse tree is the right source, unlike signature help's token + stream.** `signature.rs` reads tokens because it answers about a list that + is *being typed* and therefore does not parse. A hint decorates a file that + is being *read*: the tree already says which lists are ordered, which + positions were omitted, and exactly where each expression starts, and + re-deriving that by counting commas is how a nested `f(a, b)` shifts every + later hint one port along. A buffer that does not parse gets no hints, which + is the right failure for decoration and the wrong one for signature help. +- **A positional parameter override is a `Connection` with an empty name.** + Unlike a connection list, whose `Connections::Ordered`/`Named` says which + spelling the source used, a parameter override list carries no such node — + each entry either wrote a `.name` or did not. Pinned by a test + (`a_positional_parameter_override_writes_no_name_of_its_own`) so a parser + change cannot silently turn every override into a named one. +- **A mixed parameter list gets nothing.** `#(8, .DEPTH(16))` is illegal + SystemVerilog and perfectly typeable. Hinting only the positional half would + be claiming to know which entry `8` lands on in a list whose own author has + stopped counting; the whole list is left alone. +- **An instance array hints like a single instance.** `sub u [3:0] (a, b)` + connects the same ports, one slice per instance; the names do not change. +- **A gate primitive gets nothing.** `and (q, a, b)` is a + `GateInstantiation` — a different AST node, never reached by this module — + and the language gives its terminals no names to show. +- **`.*` is a named list.** The parser spells it as a `Connections::Named` + entry, so it is skipped with every other named list; there is no position + for it to name anyway. +- **A plan is fetched per request, not cached across them.** Measured before + choosing — see *Cost* below. The `Plans` cache lives for the length of one + request, so a screen instantiating the same module ten times parses its + declaration once, and a defining file edited between two requests is never + read from a stale copy. +- **A hint sitting exactly on the requested range's last byte is in range.** + `TextRange::contains` excludes the end, which is right for a span of text + and wrong for a viewport. +- **A port or parameter list carrying compiler directives gets nothing.** + `instantiation_plan` unions every `` `ifdef`` arm into one flat, + declaration-ordered list (the right answer for a skeleton the user edits — + see `docs/features/refactor-instantiate/README.md`'s `` `ifdef`` policy). + No single configuration has all of those entries, so a positional hint + drawn against the union names the wrong port under any one configuration — + found in QA (2026-08-24) and fixed the same day; see the QA log. + +## Handshakes + +- **Consumes `vlog_refactor`** — `module_definition` and `instantiation_plan`, + both unchanged, both already public for M4. Nothing new is asked of the + crate: this feature needs exactly the `PlanPort::name`/`PlanParam::name` + lists signature help already reads, and every refusal + `instantiation_plan` can return is swallowed silently here rather than + shown, because a hint has no place to show a sentence. +- **Consumes `vlog_parser::ast`** — `Instantiation`, `Instance`, + `Connections`, `OrderedConn`, `Connection`, and the generate-block nodes the + walk descends through. Read-only; `Expr::span` is what a hint's position is + computed from. +- **Consumes `vfmt_server::state`** — `Workspace::document` for the buffer's + tree, `Workspace::index`/`text_of` for the defining file, exactly as + `signature.rs` does. Nothing in `state.rs` was changed: no cross-request + cache was added, so the workspace stays immutable through this handler. +- **Promises `vfmt_server`** — `inlay::inlay_hints` never panics, never + returns a hint outside the requested range, and never returns a hint whose + label is not a port or parameter name the module's declaration actually + writes. +- **`editors/vscode` needs no change.** `vscode-languageclient` provides the + inlay-hint feature off the advertised capability; the extension sets no + `initializationOptions` that would suppress it. `editors/vscode/smoke.js` + checks a fixed list of capability names and was deliberately left untouched + (it is editor-packaging's file, not this feature's) — it still passes. If + the lead wants `inlayHintProvider` in that list, it is a one-line addition + there. + +## What it looks like + +`sub.sv` declares: + +```systemverilog +module sub #( + parameter int WIDTH = 8, + parameter int DEPTH = 16 +) ( + input logic clk, + input logic rst_n, + input logic [WIDTH-1:0] data +); +``` + +and `top.sv` writes: + +```systemverilog + sub #(4, 8) u1 (clk_i, rst_ni, data_q); +``` + +The editor draws: + +``` + sub #(WIDTH: 4, DEPTH: 8) u1 (clk: clk_i, rst_n: rst_ni, data: data_q); + ^^^^^^^ ^^^^^^ ^^^^ ^^^^^^ ^^^^^ + ghost labels, `paddingRight`, `InlayHintKind::PARAMETER` +``` + +Nothing is drawn on `sub u2 (.clk(clk_i), ...)`, on `sub u3 (.*)`, on the +empty position of `sub u4 (a, , c)` — where `c` is still labelled `data`, +because an omitted position still counts — or on the fourth connection of a +three-port module. + +## Cost + +Inlay hints fire on every scroll, so the number was measured before the design +was settled rather than after. Release build, warm workspace, this machine: + +| scenario | mean | +|---|---| +| `corpus/opentitan/.../uart_reg_top.sv` — 1916 lines, 63 instantiations, all **named** | **0.005 ms** | +| synthetic: 100 **distinct** modules ordered-instantiated, median-sized (~90-line) definitions, whole file at once, 700 hints | **30.8 ms** | +| the same, one 40-line screen — 40 distinct modules, 280 hints | **12.2 ms** | +| the same, with 400-line definitions instead (≈4.5× the corpus median) — one 40-line screen | 52.2 ms | + +Two things the table says. First, the cost is *entirely* the plan fetch: a +file with no ordered lists costs one tree walk and nothing else, and real RTL +is overwhelmingly named. Counted over the whole corpus with this module's own +walk (throwaway test, run and deleted): **860 files, 45 non-empty ordered +connection lists in 4 files against 945 named ones, and 69 ordered parameter +override lists against 668 named**. Second, what a request pays for is the +number of **distinct modules visible**, not the number of hints: the plan +cache collapses repeats, and the range scope means an instantiation off-screen +is never looked up at all. + +So: parse-on-request, no cross-request cache. The realistic worst case — a +screen showing forty different ordered instantiations, which no RTL file in +the corpus comes near — is 12 ms, well inside the budget. The last row is the +honest cliff: definitions 4.5× the corpus median, forty of them on one screen, +would cost 52 ms. If that shape is ever met in the wild, the fix is a plan +cache keyed on the index generation, which needs a `&mut Workspace` in the +request path and brings a staleness question (an unsaved edit to the defining +buffer) that is not worth paying for today. + +## Status / TODO + +- [x] `crates/vfmt_server/src/inlay.rs`: `inlay_hints`, the ordered-list site + collection for both ports and parameters, the per-request `Plans` cache, + the instantiation walk +- [x] `inlayHintProvider` in `main.rs`, no `resolveProvider`; the dispatch arm + in `server.rs` +- [x] Range scoping, end-inclusive +- [x] Silence on every uncertainty: unknown module, ambiguous duplicates, + named/`.*`/empty/mixed lists, connections past the last port, a buffer + that does not parse, a directive-carrying (`` `ifdef``) port or + parameter list (found in QA, fixed same day — see QA log) +- [x] Gate primitives skipped; instance arrays and multi-instance declarations + hinted; `bind`'s instantiation reached +- [x] Unit tests (26) and one e2e stdio round trip asserting exact labels, + positions, kind and padding +- [x] Cost measured over a corpus file and a synthetic worst case; harness run + and deleted +- [x] `cargo fmt --all -- --check`, `cargo clippy --all-targets`, + `cargo test --workspace`, `editors/vscode/smoke.js` +- [x] `docs/features/vfmt-server/README.md` capability table + work log +- [ ] Not done, backlog: a cross-request plan cache keyed on the index + generation (see *Cost*); type hints, value hints and any other hint kind + (deliberately out of scope — this milestone is exactly the two). + +## Work log + +- **2026-08-24 (dev)** — read M4's README, `signature.rs`, `ports.rs` and + `convert.rs` first, then the parser's `Instantiation`/`Connections` nodes. + + **Design decision 1 — the tree, not the token stream.** The brief points at + `signature.rs` as the closest cousin, and it is, but its comma-counting is + the wrong machine for this job. Signature help answers mid-keystroke about + text that does not parse yet; a hint request arrives about text the user is + reading, where `doc.tree` already holds `Connections::Ordered(...)` with a + span per entry. Counting commas would have re-derived — and eventually got + wrong — what the parser already decided: which lists are ordered, where an + omitted position is, and that the commas inside `f(a, b)` are not + connection separators. The nested-call test that pins this + (`commas_inside_a_connected_expression_do_not_shift_a_position`) passes by + construction rather than by a depth counter, which is the point. + + **Design decision 2 — the plan is fetched only for sites that are on + screen.** The range filter runs *before* the lookup, not after, so scrolling + past an instantiation of a module never parses that module's file. This is + what makes the per-screen number a third of the whole-file one in the table + above rather than equal to it. + + **Design decision 3 — a per-request cache, and no more.** Measured both + ends (see *Cost*) before deciding. A cross-request cache would need a + `&mut Workspace` in a handler that has no other reason to want one, plus an + invalidation story for a defining file being edited in another tab; the + measurement says it buys nothing on any workload the corpus contains, so it + is recorded as backlog with the number that would justify it. + + **A mixed parameter list is silent, which is a judgement call.** The brief + says "mixed illegal lists → sane". Hinting the positional half of + `#(8, .DEPTH(16))` was the alternative; it is exactly the case where the + reader cannot tell whether the author meant the entries to shift, so vfmt + says nothing rather than something confident. + + **`bind` is included.** `bind u_dut sub u_chk (a, b);` carries an ordinary + instantiation, connection list and all, so the walk descends into it. One + match arm; nothing else about `bind` is touched. + + **Files touched.** New: `crates/vfmt_server/src/inlay.rs`, this README. + Edited: `crates/vfmt_server/src/main.rs` (the module declaration, the + capability, two tests), `crates/vfmt_server/src/server.rs` (one dispatch + arm and its imports), `crates/vfmt_server/tests/e2e.rs` (one new test), + `docs/features/vfmt-server/README.md` (capability table and work log). + + **Not touched, deliberately:** `TODO.md`, the umbrella checklist in + `docs/features/refactor/README.md`, `signature.rs`, `completion.rs`, + `state.rs`, `vlog_refactor`, `editors/vscode`. No version bump — 0.5.0 comes + with M14. + + **Gates.** `cargo fmt --all -- --check` clean, `cargo clippy --all-targets` + zero warnings, `cargo test --workspace` green at **1358 passed, 0 failed** + (1330 before; 26 unit tests in `inlay.rs`, 1 capability test in `main.rs`, + 1 e2e round trip). `node editors/vscode/smoke.js` against the release + binary: OK. No new dependencies. No commits. + +## QA log + +- **2026-08-24 (QA)** — read this README, `refactor-instantiate/README.md` + (for `instantiation_plan`'s `` `ifdef`` policy and non-ANSI handling), and + `inlay.rs` end to end before touching anything. + + **Gates.** `cargo fmt --all -- --check`, `cargo clippy --all-targets + --workspace`, `cargo test --workspace` all clean before any QA change — + **1358 passed, 0 failed**, matching the dev's number exactly. `node + editors/vscode/smoke.js target/release/vfmt-server` — OK; confirmed the + script's fixed capability list (`main.rs`'s check, mirrored in the smoke + script) does not include `inlayHintProvider`, matching the disclosed, + deliberate handshake gap. + + **Finding — HIGH, fixed.** A module whose port or parameter list carries + `` `ifdef``/`` `else`` directives got hints built from + `InstantiationPlan`'s **union of every arm**, which is a shape no single + build configuration ever has. Repro: `crates/vfmt_server/src/inlay.rs`, + test `an_ifdef_carrying_declaration_gets_no_hints_rather_than_a_wrong_one` + — `module sub (`ifdef CFG_A input logic a, `else input logic b, `endif + input logic clk);` gives `plan.ports == [a, b, clk]` (verified directly + against `vlog_refactor::instantiation_plan`, `crates/vlog_refactor/src/ + instantiate.rs:144`). Before the fix, `sub u1 (x, y)` was hinted `a: x, b: + y` — wrong under *both* real configurations, since the true second port is + always `clk`, never `b`. This is exactly the case the feature's own Goal + section rules out ("A wrong port name drawn in ghost text is worse than no + port name, because the reader has no way to tell it is wrong"), and it was + undisclosed: no Assumption, Handshake, or test mentioned `` `ifdef`` at + all, despite `instantiation_plan` warning about exactly this + (`plan.warnings`) and M4's own README treating the same directive shape as + a first-class case worth a warning. `Plans::read` + (`crates/vfmt_server/src/inlay.rs:192`) called + `vlog_refactor::instantiation_plan(...).ok()` and discarded `plan.warnings` + without ever inspecting it. **Fix applied**: `Plans::read` now returns + `None` when `plan.warnings` is non-empty, so a directive-carrying list is + silent exactly like an unknown module. Two regression tests added + (`an_ifdef_carrying_declaration_gets_no_hints_rather_than_a_wrong_one`, + `an_ifdef_carrying_parameter_list_gets_no_hints_either`); one Assumptions + bullet added above documenting the behavior. Full suite re-green after the + fix: **1366 passed, 0 failed** (1358 + 8 new permanent tests; 2 more perf + tests added `#[ignore]`d, not counted in "passed"). `cargo fmt`/`clippy` + clean, smoke.js re-run OK against a rebuilt release binary. + + **Everything else tried to break, and did not:** + - *Omitted position, off-by-one.* `u (a, , c)` — already covered by the + dev's own test; independently re-derived by hand against `plan.ports` + and confirmed the third port's name lands on `c`, not shifted. + - *More connections than ports.* Extras correctly unhinted (dev's test, + re-verified). + - *Non-ANSI header.* New test `a_non_ansi_header_definition_hints_correctly` + — `module nasub (clk, rst_n, data); input clk; ...` hints exactly + `["clk:", "rst_n:", "data:"]`. `ports()` in `instantiate.rs:386` branches + on `PortList::NonAnsi` correctly; nothing inlay-specific needed. + - *Parameterized instantiation, port type depends on a parameter.* New + test `a_port_whose_width_depends_on_a_parameter_still_hints_by_name_only` + — `[WIDTH-1:0] data` port, `#(16)` override — no crash, correct labels; + the label is only ever `port.name`, never the type. + - *Recursive/self instantiation.* New test + `a_self_instantiating_module_does_not_crash` — `module top; top u1 + (clk); endmodule` does not loop or panic (the module has no declared + ports, so the honest answer is no hints; the point was survival, not a + label). + - *`defparam`.* No `#( ... )` node exists for `defparam u1.WIDTH = 4;`, so + `param_sites` never sees it; port hints on the same instantiation are + unaffected. Confirmed with an ad hoc probe (not kept as a permanent + test — it exercises no code path the existing suite doesn't already + cover). + - *Emoji inside a nested call argument.* New test + `a_comment_nested_inside_a_connected_expression_does_not_shift_utf16_columns` + — `f(/* 🎉é */ a, b)` as one connection: the comma inside stays a + non-separator (per the dev's existing nested-call design) and the next + hint's column (29) is correct in UTF-16 units, surrogate pair included. + - *Mixed positional/named recovery shapes.* Dev's existing test already + covers both parser-recovery shapes and asserts the weaker "no hint on a + named entry" invariant; agree that is the right assertion strength. + + **Range scoping.** + - New test + `a_range_starting_mid_instantiation_hints_only_the_visible_connections` — + a range starting after `clk,` on `sub u1 (clk, rst_n, data);` hints + `rst_n` and `data` only. The filter is **per-site**, not + per-instantiation: confirms the code's actual behavior (`Hints::paint` + filters each `Site` independently) is a bit finer-grained than the + README's Design-decision-2 prose implies ("a scroll cost the visible + instantiations"), but it is the more correct behavior for a viewport, so + no fix — just documented here since the prose undersells it. + - Empty range and whole-file: covered by the dev's own + `only_the_requested_range_is_hinted` test; re-run and agree. + + **Perf.** Rebuilt a cheap harness (`inlay::tests::qa_perf`, `#[ignore]`d, + not part of the default suite — run with `cargo test --release -p + vfmt_server --bin vfmt-server qa_perf -- --ignored --nocapture`) rather + than driving the real binary over stdio, since the library call is what + the dev's own numbers measure too: + - 40 distinct ~90-line ordered modules, one 40-line screen, 840 hints: + **~2.8ms** release / this machine — same order of magnitude as the + README's 12.2ms for the same shape (this run came in faster; not a + concern, the direction that matters is "small," and it is). + - The same module instantiated 100× ordered, whole file, 300 hints: + **~163µs** — confirms the plan cache collapses repeats to one parse + (**O(distinct modules)**, not O(instances)), matching the Cost section's + claim. + + **Staleness.** New test + `an_open_unsaved_buffer_of_the_defining_file_wins_over_disk` — an unsaved + `didChange`-style edit to the *defining* module's open buffer (renaming + `clk` to `clk_renamed`, disk left untouched) is what a hint request in the + instantiating file reads. Matches the Assumptions claim ("a defining file + edited between two requests is never read from a stale copy") and is now + pinned by a test rather than only asserted in prose. + + **Verdict: ship-after-fixes — the ifdef finding above is fixed and tested + in this same change; nothing else found rises above a documentation nit, + and those are addressed inline (the Assumptions bullet above, this log).** + +## Review + +**2026-08-24 — lead.** Reviewed after QA; gates run independently (1366 +tests, 0 failures, clippy silent). The tree-walk-over-comma-counting +argument is correct and well made — hints decorate parsed text, so the +tree already answers what signature help must guess. QA's HIGH find was +the round's real work: the `ifdef` union that is right for an editable +skeleton is confidently wrong for a read-only ghost label, and the +applied fix (a plan with warnings is treated like every other +uncertainty — silence) is exactly the feature's own stated invariant; +the in-code comment explaining the asymmetry with M4 is the kind of +comment worth keeping. Verified the fix and its two regression tests +myself. O(distinct-modules) caching confirmed by QA at 163µs for 100 +instances of one module. Accepted; M8 checked off in the umbrella plan +and TODO.md §8. diff --git a/docs/features/refactor/README.md b/docs/features/refactor/README.md index 72a8bf5..894996a 100644 --- a/docs/features/refactor/README.md +++ b/docs/features/refactor/README.md @@ -151,7 +151,7 @@ built but nothing consumes yet. Ordered by value ÷ cost: same data on a standard capability. Cheapest win on this list. - [x] **Document highlight** — cursor on a symbol highlights its other occurrences; one `references_of` call, no new analysis. -- [ ] **Inlay hints for ordered connections** — `u (clk, rst_n, data)` +- [x] **Inlay hints for ordered connections** — `u (clk, rst_n, data)` shows `.clk:`/`.rst_n:` ghost labels from the instantiated module's definition (same index facts as M4); parameter names on ordered `#(...)` overrides too. High everyday value in RTL review. @@ -262,6 +262,7 @@ commit — in order: - [x] M6 completion-templates — done, QA clean first pass, reviewed - [x] Backlog triage after M6 — LSP-parity gap list added, 2026-08-24 - [x] M7 references-nav — done, QA clean first pass, reviewed +- [x] M8 inlay-hints — done, one QA HIGH fixed in-round, reviewed ## Work log diff --git a/docs/features/vfmt-server/README.md b/docs/features/vfmt-server/README.md index f2cc895..bfb4ad0 100644 --- a/docs/features/vfmt-server/README.md +++ b/docs/features/vfmt-server/README.md @@ -30,6 +30,7 @@ looks like language knowledge in here is a bug or a `Handshake` request. | `textDocument/rename` | `vlog_refactor::rename` | Cross-file `WorkspaceEdit` (`changes`); warnings go out on `window/logMessage`; refusals are `RequestFailed`. See `docs/features/refactor-rename/README.md` | | `textDocument/completion` | `vlog_refactor::instantiation_plan` | Module hinting: one item per indexed module, inserting the whole instantiation skeleton as a snippet (plain text for a client that did not advertise `snippetSupport`). Capped at 64 items, `isIncomplete` when truncated; declines every position that is not module-item. See `docs/features/refactor-instantiate/README.md` | | `textDocument/signatureHelp` | `vlog_refactor::instantiation_plan` | The instantiated module's ports (or, inside `#( ... )`, its parameters) with the active one highlighted — by name for a named list, by position for an ordered one. Triggers: `(` and `,`. Same feature README | +| `textDocument/inlayHint` | `vlog_refactor::instantiation_plan` | Ghost port names on an **ordered** connection list (`u1 (clk, rst_n)`) and parameter names on ordered `#( ... )` overrides, read from the instantiated module's declaration. Range-scoped; named lists, `.*`, omitted positions, connections past the last port, gate primitives and modules the index cannot resolve get nothing at all — a hint is decoration and never guesses. No `resolveProvider`. See `docs/features/inlay-hints/README.md` | | `workspace/symbol` | `WorkspaceIndex::workspace_symbols` | Capped at 256 hits | Deferred, deliberately, and named in Status/TODO below: ~~range formatting @@ -442,11 +443,48 @@ list to `vlog_parser::KEYWORDS`. Rationale and inventory: `docs/features/references-nav/README.md`. - [x] ~~**Not done:**~~ `vfmt.toml` discovery, `.gitignore`-aware indexing — delivered by vfmt-core-lift (both Handshakes below marked DELIVERED). +- [x] `textDocument/inlayHint` — delivered by **inlay-hints** (M8): port and + parameter names on ordered connection lists, off the same + `instantiation_plan` completion and signature help read. + `docs/features/inlay-hints/README.md`. - [ ] **Not done:** editor packaging (the VS Code extension and the `lspconfig` snippet are their own TODO.md §6 item). ## Work log +### 2026-08-24 — dev agent (M8 inlay-hints) + +- **One new capability, one new module, nothing else moved.** + `inlayHintProvider` is advertised as `InlayHintOptions` with no + `resolveProvider` (every hint is returned complete), `server.rs` gained one + dispatch arm, and `crates/vfmt_server/src/inlay.rs` holds the whole answer. + No engine change: `vlog_refactor::module_definition` + + `instantiation_plan` were already public for M4, and this feature reads only + the port/parameter **names** out of the plan. +- **The one architectural difference from `signature.rs`, stated here because + the two look like they should share code**: signature help reads the token + stream because it answers about a half-typed list; inlay hints read + `doc.tree`, because a hint decorates text that parses and the tree already + knows which lists are ordered, where each expression starts, and which + positions were omitted. Sharing a comma counter between them would have made + the hint answer worse, not the code smaller. +- **Cost measured before the design was fixed**, not after: 0.005 ms over a + 1916-line corpus file, 12.2 ms for a 40-line screen showing forty *distinct* + ordered instantiations, 30.8 ms for a hundred of them at once. Plans are + cached for the length of one request and not across requests; the number + that would justify a cross-request cache, and the staleness it would bring, + are written up in the feature README's *Cost* section. +- **Nothing in `state.rs` was touched**, so the workspace is still immutable + through every read handler. `editors/vscode` needs no change either — the + language client picks the feature up from the advertised capability — and + `smoke.js` was deliberately left alone (its capability list belongs to + editor-packaging); it still passes against the release binary. +- **Results.** `cargo test --workspace`: **1358 passed, 0 failed** (1330 + before — 26 unit tests in `inlay.rs`, one capability test in `main.rs`, one + e2e stdio round trip). `cargo clippy --all-targets`: silent. + `cargo fmt --all -- --check`: clean. No new dependencies, no version bump + (0.5.0 belongs to M14), no commits. + ### 2026-08-24 — dev agent (0.4.1, fence audit only) Owned by `docs/features/editor-packaging/README.md`; noted here because it