diff --git a/crates/lucisv_server/src/hover.rs b/crates/lucisv_server/src/hover.rs index 6406080..0ec2886 100644 --- a/crates/lucisv_server/src/hover.rs +++ b/crates/lucisv_server/src/hover.rs @@ -12,11 +12,13 @@ use lsp_types::{Hover, HoverContents, MarkupContent, MarkupKind, Uri}; use vlog_parser::defines::Define; use vlog_parser::token::Token; -use vlog_parser::TextRange; -use vlog_semantic::{Definition, FileId, Symbol}; +use vlog_parser::{LineIndex, TextRange}; +use vlog_semantic::{Def, Definition, FileId, Symbol}; +use crate::convert::Positions; use crate::expand::{self, Expansion}; use crate::locate::{display_name, line_number}; +use crate::nav::indexed_def_for_symbol; use crate::state::{Document, Workspace}; use crate::symbols::kind_label; @@ -172,6 +174,11 @@ fn symbol_hover(ws: &Workspace, doc: &Document, offset: u32) -> Option { match doc.external.definition_of(&doc.semantics, offset)? { Definition::Local(symbol) => Some(markdown(doc, local_text(doc, symbol), range)), Definition::External(defs) => { + // Every `External` answer comes from a reference (`definition_of`), + // and that reference's name is the *declared* name — `WIDTH` for a + // `p::WIDTH`, `clk` for a `.clk(...)` — which is what the guard in + // `declaration_snippet` checks the other file's text against. + let name = doc.semantics.reference_at(offset).map(|r| r.name.as_str()); let mut parts = Vec::with_capacity(defs.len()); for def in defs { let label = kind_label(def.kind); @@ -183,7 +190,11 @@ fn symbol_hover(ws: &Workspace, doc: &Document, offset: u32) -> Option { None => display_name(path), }) .unwrap_or_else(|| "the workspace".to_string()); - parts.push(format!("**{label}** — declared in `{where_}`")); + let mut part = format!("**{label}** — declared in `{where_}`"); + if let Some(snippet) = name.and_then(|name| declaration_snippet(ws, def, name)) { + part.push_str(&snippet); + } + parts.push(part); } Some(markdown(doc, parts.join("\n\n"), range)) } @@ -201,6 +212,138 @@ fn local_text(doc: &Document, symbol: &Symbol) -> String { ) } +// ---------------------------------------------------------------------- +// the declaration behind a cross-file answer +// ---------------------------------------------------------------------- + +/// How much of a declaration a card shows. Both limits are real: a `decl_span` +/// can cover a whole module body, and one line of a netlist can be megabytes. +const SNIPPET_LINES: usize = 5; +const SNIPPET_CHARS: usize = 400; + +/// The source of a declaration in another file, fenced for the card. +/// +/// The index holds only `{file, name_span, kind}` and no text +/// (`docs/features/workspace-index/README.md`), so the line is fetched here, +/// at hover time, from whichever text the span is actually valid against. +/// +/// `None` — no snippet, today's card unchanged — wherever the two could +/// disagree: an unreadable file, a span the text does not cover, or a span +/// covering something other than the name that was hovered. A hover that +/// prints the wrong line is worse than one that prints none. +fn declaration_snippet(ws: &Workspace, def: &Def, name: &str) -> Option { + let path = ws.index().path(def.file)?; + match ws.document_for_path(path) { + // The file is open, so the index's span is against its *last saved* + // text and an unsaved edit above the declaration has already moved it. + // Find the same declaration logically instead, exactly as `nav.rs` + // does, and read the live buffer at the live span. + Some(target) => { + let symbol = live_symbol(ws, target, def, name)?; + if !spells_exactly(&target.text, symbol.name_span, name) { + return None; + } + fenced(target.positions().whole_lines(symbol.decl_span)) + } + // Not open: disk text is what the index was built from, so the + // recorded span is the one to trust. + None => { + let text = ws.text_of(path)?; + if !spells_exactly(&text, def.name_span, name) { + return None; + } + let index = LineIndex::new(&text); + fenced(Positions::new(&text, &index).whole_lines(def.name_span)) + } + } +} + +/// The live symbol in an open buffer that *is* this indexed declaration. +fn live_symbol<'a>( + ws: &Workspace, + target: &'a Document, + def: &Def, + name: &str, +) -> Option<&'a Symbol> { + target.semantics.symbols().iter().find(|symbol| { + symbol.name == name && indexed_def_for_symbol(ws, target, symbol) == Some(def) + }) +} + +/// The text a span covers, or `None` when the span is not inside `text` on +/// character boundaries — which means the span and the text disagree. +fn span_text(text: &str, span: TextRange) -> Option<&str> { + text.get(span.start as usize..span.end as usize) +} + +/// Whether `span` spells `name` exactly — not merely a prefix or a suffix of +/// a longer identifier that now sits there. +/// +/// QA (hover-declarations, 2026-08-27): a length-equality check alone is not +/// enough. `def.name_span` is a *fixed-length* byte range recorded when the +/// index was built; an edit that extends the identifier in place (`addr` → +/// `addr2`, with no reindex yet) leaves those same bytes still spelling the +/// old, shorter name as a prefix. `span_text` would report a match, and the +/// card would show `addr2`'s declaration under `addr`'s name — the exact +/// masked-corruption shape the guard exists to close. Requiring the +/// character immediately outside the span (on either side, if there is one) +/// to not continue an identifier turns that prefix/suffix match back into a +/// miss, without needing anything more than the same "is this still a name +/// character" question a lexer already answers for `$`, `_` and alnum. +fn spells_exactly(text: &str, span: TextRange, name: &str) -> bool { + if span_text(text, span) != Some(name) { + return false; + } + let before = text.get(..span.start as usize).and_then(|s| s.chars().next_back()); + let after = text.get(span.end as usize..).and_then(|s| s.chars().next()); + !before.is_some_and(continues_a_name) && !after.is_some_and(continues_a_name) +} + +/// Whether `c` can continue an identifier once one has started. Used only to +/// confirm a name span's boundaries against what surrounds it — not to lex +/// an identifier from scratch, so it does not need to know what may *start* +/// one. +fn continues_a_name(c: char) -> bool { + c.is_ascii_alphanumeric() || c == '_' || c == '$' +} + +/// One declaration's lines, as the card shows them: cut to size and fenced +/// with the grammar's language id, which is the only thing that colours a +/// hover card (see the pinned fence tag in `define_text`). +fn fenced(lines: &str) -> Option { + let (text, note) = cut_to_size(lines); + if text.is_empty() { + return None; + } + let mut out = format!("\n\n```systemverilog\n{text}\n```"); + if let Some(note) = note { + out.push_str(&format!("\n\n{note}")); + } + Some(out) +} + +/// A declaration cut to what a hover card can hold, with the note naming +/// whichever limit cut it. Trailing blank space goes either way, like +/// `local_text`'s; leading indentation stays, so the line reads as written. +fn cut_to_size(lines: &str) -> (String, Option) { + let trimmed = lines.trim_end(); + let mut kept = trimmed; + let mut note = None; + if let Some(end) = trimmed.match_indices('\n').map(|(at, _)| at).nth(SNIPPET_LINES - 1) { + kept = &trimmed[..end]; + note = Some(format!("*shown to {SNIPPET_LINES} lines*")); + } + if let Some((end, _)) = kept.char_indices().nth(SNIPPET_CHARS) { + kept = &kept[..end]; + note = Some(format!("*shown to {SNIPPET_CHARS} characters*")); + } + let mut text = kept.trim_end().to_string(); + if note.is_some() { + text.push_str(" …"); + } + (text, note) +} + /// The span the hover card should highlight: the name under the cursor. fn hovered_name_span(doc: &Document, offset: u32) -> Option { if let Some(reference) = doc.semantics.reference_at(offset) { @@ -593,6 +736,171 @@ mod tests { let _ = fs::remove_dir_all(&dir); } + // ------------------------------------------------------------------ + // the declaration behind a cross-file answer + // ------------------------------------------------------------------ + + const PORTS: &str = + "module sub (\n input logic [7:0] addr,\n output logic ready\n);\nendmodule\n"; + + #[test] + fn a_cross_file_port_connection_shows_the_ports_own_declaration_line() { + // The ask this round answers: direction, type and width, not just a + // file and a line. + let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n"; + let (dir, ws, uri) = included("portdecl", &[("sub.sv", PORTS), ("top.sv", top)]); + let body = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover")); + assert!( + body.contains("**port** — declared in `sub.sv:2`"), + "the heading stays: got {body}" + ); + assert!( + body.contains("```systemverilog\n input logic [7:0] addr,\n```"), + "the declaration itself: got {body}" + ); + assert!(!body.contains("output logic ready"), "only its own line: got {body}"); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn a_cross_file_module_instance_shows_its_header_line() { + let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n"; + let (dir, ws, uri) = included("moduledecl", &[("sub.sv", PORTS), ("top.sv", top)]); + let body = text_of(&hover(&ws, &uri, at(top, "sub u")).expect("hover")); + assert!(body.contains("**module** — declared in `sub.sv:1`"), "got {body}"); + assert!(body.contains("```systemverilog\nmodule sub (\n```"), "got {body}"); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn a_package_member_shows_its_declaration_line() { + let pkg = + "package p;\n localparam WIDTH = 8;\n typedef logic [3:0] nibble_t;\nendpackage\n"; + let top = "module top;\n import p::*;\n wire [WIDTH-1:0] a;\n nibble_t n;\nendmodule\n"; + let (dir, ws, uri) = included("pkgdecl", &[("p.sv", pkg), ("top.sv", top)]); + + let body = text_of(&hover(&ws, &uri, at(top, "WIDTH-1")).expect("hover")); + assert!(body.contains("**parameter** — declared in `p.sv:2`"), "got {body}"); + assert!(body.contains("```systemverilog\n localparam WIDTH = 8;\n```"), "got {body}"); + + let body = text_of(&hover(&ws, &uri, at(top, "nibble_t n")).expect("hover")); + assert!( + body.contains("```systemverilog\n typedef logic [3:0] nibble_t;\n```"), + "a typedef reads the same way: got {body}" + ); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn an_unsaved_edit_that_moved_the_declaration_is_read_at_its_live_span() { + // The index's span is against the last *saved* text. Reading it out of + // the open buffer would print whatever the shifted offsets now cover. + let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n"; + let saved = "module sub (\n input logic [7:0] addr\n);\nendmodule\n"; + let (dir, mut ws, uri) = included("livemove", &[("sub.sv", saved), ("top.sv", top)]); + let sub_uri = path_to_uri(&dir.join("sub.sv")).expect("uri"); + let edited = "// two lines\n// pushed it down\nmodule sub (\n input logic [15:0] addr\n);\nendmodule\n"; + ws.set_document(sub_uri, edited.to_string()); + + let body = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover")); + assert!( + body.contains("```systemverilog\n input logic [15:0] addr\n```"), + "the live line, width and all: got {body}" + ); + assert!(!body.contains("[7:0]"), "not the saved one: got {body}"); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn a_stale_indexed_span_drops_the_snippet_rather_than_showing_the_wrong_line() { + // The file changed on disk under a live index — a rescan the server has + // not run yet. The recorded span now covers something that is not the + // name, so there is nothing honest to print. + let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n"; + let saved = "module sub (\n input logic [7:0] addr\n);\nendmodule\n"; + let (dir, ws, uri) = included("stalespan", &[("sub.sv", saved), ("top.sv", top)]); + fs::write(dir.join("sub.sv"), format!("// {}\n{saved}", "x".repeat(40))).expect("rewrite"); + + let body = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover")); + assert!(body.contains("**port** — declared in"), "today's card, intact: got {body}"); + assert!(!body.contains("```"), "and no snippet at all: got {body}"); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn an_open_buffer_that_no_longer_declares_the_name_drops_the_snippet() { + // The other half of the guard: the target file is open and its live + // text has renamed the port away, so no live symbol is that indexed + // declaration and nothing may be printed for it. + let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n"; + let saved = "module sub (\n input logic [7:0] addr\n);\nendmodule\n"; + let (dir, mut ws, uri) = included("livemiss", &[("sub.sv", saved), ("top.sv", top)]); + let sub_uri = path_to_uri(&dir.join("sub.sv")).expect("uri"); + ws.set_document( + sub_uri, + "module sub (\n input logic [7:0] renamed\n);\nendmodule\n".to_string(), + ); + + let body = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover")); + assert!(body.contains("**port** — declared in"), "got {body}"); + assert!(!body.contains("```"), "got {body}"); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn a_very_long_declaration_line_is_cut_with_a_note() { + // Netlist lines have no bound; a hover card does. + let filler = "z".repeat(SNIPPET_CHARS + 100); + let sub = format!("module sub (\n input logic [7:0] addr /* {filler} */\n);\nendmodule\n"); + let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n"; + let (dir, ws, uri) = included("longline", &[("sub.sv", &sub), ("top.sv", top)]); + + let body = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover")); + assert!(body.contains("input logic [7:0] addr"), "the useful half survives: got {body}"); + assert!(body.contains(" …\n```"), "cut with an ellipsis"); + assert!(body.contains(&format!("*shown to {SNIPPET_CHARS} characters*")), "and says so"); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn a_declaration_spanning_many_lines_is_cut_at_the_line_limit() { + // A module's `decl_span` is its whole body, which the live path widens + // to — fine for a port, a card-swallowing wall for a big module. + let mut sub = String::from("module sub (\n input logic [7:0] addr\n);\n"); + for n in 0..20 { + sub.push_str(&format!(" wire w{n};\n")); + } + sub.push_str("endmodule\n"); + let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n"; + let (dir, mut ws, uri) = included("longdecl", &[("sub.sv", &sub), ("top.sv", top)]); + let sub_uri = path_to_uri(&dir.join("sub.sv")).expect("uri"); + ws.set_document(sub_uri, sub.clone()); + + let body = text_of(&hover(&ws, &uri, at(top, "sub u")).expect("hover")); + assert!(body.contains("```systemverilog\nmodule sub ("), "got {body}"); + assert!(body.contains(&format!("*shown to {SNIPPET_LINES} lines*")), "got {body}"); + assert!(!body.contains("w19"), "the body is not printed: got {body}"); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn two_files_declaring_one_name_each_get_their_own_snippet() { + let top = "module top;\n dup u (.*);\nendmodule\n"; + let (dir, ws, uri) = included( + "dupdecl", + &[ + ("a.sv", "module dup (input logic a_clk);\nendmodule\n"), + ("b.sv", "module dup (input logic b_clk);\nendmodule\n"), + ("top.sv", top), + ], + ); + let body = text_of(&hover(&ws, &uri, at(top, "dup u")).expect("hover")); + assert!(body.contains("a.sv:1") && body.contains("b.sv:1"), "both candidates: got {body}"); + assert!(body.contains("input logic a_clk"), "got {body}"); + assert!(body.contains("input logic b_clk"), "each with its own line: got {body}"); + let _ = fs::remove_dir_all(&dir); + } + #[test] fn hovering_whitespace_returns_nothing() { let text = "module m;\n\n wire a;\nendmodule\n"; @@ -713,3 +1021,340 @@ mod qa_findings { let _ = fs::remove_dir_all(&dir); } } + +/// QA (hover-declarations, 2026-08-27): adversarial probes against +/// `declaration_snippet`. See the QA log in +/// `docs/features/hover-declarations/README.md` for the writeup of each. +#[cfg(test)] +mod qa_hover_declarations { + use super::*; + use crate::uri::path_to_uri; + use std::fs; + use std::path::PathBuf; + use std::str::FromStr; + + fn temp_dir(tag: &str) -> PathBuf { + let dir = + std::env::temp_dir().join(format!("lucisv_qa_hoverdecl_{tag}_{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).expect("temp dir"); + dir + } + + /// Angle 1: the disk-path guard slices `def.name_span` — a *fixed-length* + /// byte range, the old name's length, taken when the index was built — + /// and compares it for equality with the hovered name. It never checks + /// what comes immediately *after* that range. So an edit that extends the + /// declared identifier by appending characters (no reindex yet) leaves + /// the first `name.len()` bytes at the old offset still spelling the old + /// name — the guard passes — while the *actual* identifier at that + /// position is now a different, longer one that the file no longer + /// declares under the hovered name at all. + /// + /// This is exactly the "same name at the stale span by coincidence" + /// attack the QA charter asks for, and it succeeds: the card claims to + /// show `addr`'s declaration and instead shows `addr2`'s, with no + /// indication anything is wrong. FINDING (see QA log, MEDIUM): the guard + /// needs a word-boundary check, not just a fixed-length substring match. + #[test] + fn a_disk_edit_that_only_appends_to_the_name_defeats_the_guard() { + let saved = "module sub (\n input logic [7:0] addr\n);\nendmodule\n"; + let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n"; + let (dir, ws, uri) = included("guardappend", &[("sub.sv", saved), ("top.sv", top)]); + // Same bytes up to and including "addr", then more identifier + // characters glued directly on — the stale span still lines up with + // "addr" as a prefix of the new, longer name. + let corrupted = "module sub (\n input logic [7:0] addr2\n);\nendmodule\n"; + let prefix_len = saved.find("addr").unwrap() + 4; + assert_eq!( + &corrupted[..prefix_len], + &saved[..prefix_len], + "the attack requires the stale span to still land on the same bytes" + ); + fs::write(dir.join("sub.sv"), corrupted).expect("rewrite"); + + let body = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover")); + let shows_wrong_declaration = body.contains("addr2"); + if shows_wrong_declaration { + panic!( + "GUARD DEFEATED: the card for `.addr(...)` shows `addr2`'s line, \ + not `addr`'s (which no longer exists) — got {body:?}" + ); + } + } + + fn included(tag: &str, files: &[(&str, &str)]) -> (PathBuf, Workspace, Uri) { + let dir = temp_dir(tag); + for (name, text) in files { + fs::write(dir.join(name), text).expect("write"); + } + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let top = dir.join("top.sv"); + let uri = path_to_uri(&top).expect("uri"); + ws.set_document(uri.clone(), fs::read_to_string(&top).expect("read")); + (dir, ws, uri) + } + + fn at(text: &str, needle: &str) -> u32 { + text.find(needle).expect("needle present") as u32 + } + + fn text_of(hover: &Hover) -> String { + match &hover.contents { + HoverContents::Markup(m) => m.value.clone(), + other => panic!("expected markup, got {other:?}"), + } + } + + /// Angle 3: two live declarations of the same port name in an open + /// buffer (a transient state while editing — e.g. mid-refactor before the + /// stale one is deleted). The index still has one persisted `Def` for the + /// name, so `indexed_def_for_symbol` maps *either* live symbol back to + /// it, and `live_symbol`'s `.find()` picks whichever comes first in + /// `Semantics::symbols()` order. + /// + /// Not a wrong-line *lie* — the guard still requires the chosen symbol's + /// own text to spell the name, which it always does by construction — but + /// it is a silent, arbitrary choice between two candidates with no signal + /// to the user that the buffer is ambiguous. This is inherited from + /// `nav.rs`'s pre-existing matcher (unchanged by this round: "one + /// matcher, so hover and go-to-definition can never disagree"), so it is + /// filed as an accepted pre-existing limitation, not a new defect. Pinned + /// here so a future change to the matcher's tie-break is not silent. + #[test] + fn duplicate_live_declarations_of_one_name_pick_the_first_one_silently() { + let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n"; + let saved = "module sub (\n input logic [7:0] addr\n);\nendmodule\n"; + let (dir, mut ws, uri) = included("dupdup", &[("sub.sv", saved), ("top.sv", top)]); + let sub_uri = path_to_uri(&dir.join("sub.sv")).expect("uri"); + // Two ports named `addr`, different widths, in the same scope/kind. + let edited = + "module sub (\n input logic [7:0] addr,\n input logic [15:0] addr\n);\nendmodule\n"; + ws.set_document(sub_uri, edited.to_string()); + + let body = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover")); + // Exactly one of the two widths appears — never both, never neither — + // confirming the pick is total but not both fenced blocks are shown. + let has_first = body.contains("[7:0] addr"); + let has_second = body.contains("[15:0] addr"); + assert!(has_first ^ has_second, "expected exactly one candidate shown: got {body}"); + let _ = fs::remove_dir_all(&dir); + } + + /// Angle 2 (CRLF): a multi-line snippet from a CRLF file keeps the `\r` + /// on every line except the last, where `cut_to_size`'s `trim_end` + /// strips it. `local_text` (the in-file branch) has the same property — + /// this is not new to this round, but it is real: the fenced block for a + /// module header spanning multiple CRLF lines carries an embedded `\r` + /// before an interior `\n`. Cosmetic (most renderers show a fenced block + /// verbatim, so a stray `\r` is invisible or a non-issue in practice), + /// not a correctness break — filed as a low-severity finding rather than + /// a masked-corruption risk, since the text shown is still exactly the + /// bytes on disk. + #[test] + fn a_crlf_multiline_snippet_keeps_interior_carriage_returns() { + // `wide`'s `decl_span` is its whole body (a module, like `PORTS` in + // the dev's own tests), so its live-path snippet spans several CRLF + // lines and is exactly where an interior, un-trimmed `\r` would show. + // Both modules must exist at the *initial* index build — rewriting a + // module name into a file after `open_whole_workspace` without + // reindexing leaves the index not knowing that name, which is a + // workspace-setup mistake, not something this test is probing. + let wide = + "module wide (\r\n input logic a\r\n);\r\n wire w0;\r\n wire w1;\r\nendmodule\r\n"; + let top = "module top;\r\n wide u ();\r\nendmodule\r\n"; + let (dir, mut ws, uri) = included("crlfdecl", &[("wide.sv", wide), ("top.sv", top)]); + let wide_uri = path_to_uri(&dir.join("wide.sv")).expect("uri"); + // Open the target so the live path (which widens `decl_span`, the + // multi-line span) is exercised rather than the disk path. + ws.set_document(wide_uri, wide.to_string()); + + let body = text_of(&hover(&ws, &uri, at(top, "wide u")).expect("hover")); + assert!(body.contains("module wide ("), "got {body:?}"); + assert!( + body.contains("wire w0;\r\n"), + "an interior CRLF line keeps its \\r inside the fence: got {body:?}" + ); + let _ = fs::remove_dir_all(&dir); + } + + /// Angle 2: multi-byte UTF-8 content earlier in the same file (and on the + /// same line, before the declaration) must not panic `span_text` or + /// `whole_lines`. Both are `.get()`-based, so this is a belt-and-braces + /// regression pin rather than a discovered defect. + #[test] + fn multibyte_utf8_before_the_declaration_does_not_panic() { + // The identifier itself must stay ASCII (SV identifiers are), but the + // comment above it — which the widened whole-line span never reaches, + // yet whose byte length shifts every offset after it — is not. + let sub = + "// 世界 comment — üñïçødé\nmodule sub (\n input logic [7:0] addr\n);\nendmodule\n"; + let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n"; + let (dir, ws, uri) = included("utf8decl", &[("sub.sv", sub), ("top.sv", top)]); + let body = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover")); + assert!(body.contains("input logic [7:0] addr"), "got {body}"); + assert!(!body.contains("世界"), "only the declaration's own line: got {body}"); + let _ = fs::remove_dir_all(&dir); + } + + /// Angle 4: exactly `SNIPPET_LINES` lines is not cut (no note, no + /// ellipsis); one more line is. + #[test] + fn exactly_the_line_cap_is_not_cut_one_more_is() { + let mut sub = String::from("module sub (\n input logic [7:0] addr\n);\n"); + // decl_span (module header .. matching paren, widened to whole lines) + // needs to land at exactly SNIPPET_LINES lines for the boundary case; + // instead, directly probe `cut_to_size`, which is what actually owns + // the boundary and is unit-testable without fighting the parser's + // span shape. + let _ = &mut sub; + let five = "a\nb\nc\nd\ne"; + let (text, note) = cut_to_size(five); + assert_eq!(text, "a\nb\nc\nd\ne", "5 lines, unmodified: got {text:?}"); + assert!(note.is_none(), "no note at exactly the cap: got {note:?}"); + + let six = "a\nb\nc\nd\ne\nf"; + let (text6, note6) = cut_to_size(six); + assert_eq!(text6, "a\nb\nc\nd\ne …", "the first 5 lines, `f` dropped: got {text6:?}"); + assert_eq!(note6, Some("*shown to 5 lines*".to_string())); + } + + /// Angle 4: exactly `SNIPPET_CHARS` characters is not cut; one more is, + /// and the cut always lands on a character boundary even when the + /// boundary character is multi-byte. + #[test] + fn exactly_the_char_cap_is_not_cut_one_more_is_and_boundary_is_safe() { + let exact = "a".repeat(SNIPPET_CHARS); + let (text, note) = cut_to_size(&exact); + assert_eq!(text.chars().count(), SNIPPET_CHARS); + assert!(note.is_none(), "no note at exactly the cap: got {note:?}"); + + let over = "a".repeat(SNIPPET_CHARS + 1); + let (text2, note2) = cut_to_size(&over); + assert_eq!(text2, format!("{} …", "a".repeat(SNIPPET_CHARS))); + assert!(note2.is_some()); + + // The 400th character itself is multi-byte (3-byte '世'); char-based + // cutting must not split it and must not panic. + let mut mixed = "a".repeat(SNIPPET_CHARS - 1); + mixed.push('世'); + mixed.push_str("bbbb"); + let (text3, note3) = cut_to_size(&mixed); + // 400 kept chars (399 `a`s + the whole `世`, never half of it) plus the + // 2-char " …" suffix — the boundary character survives intact. + assert_eq!(text3.chars().count(), SNIPPET_CHARS + 2, "got {text3:?}"); + assert!(text3.ends_with("世 …"), "the multi-byte char is not split: got {text3:?}"); + assert!(note3.is_some()); + } + + /// Angle 2: the declared name sits at the very start of the file (offset + /// 0), with no character before it — `whole_lines`/`span_text` must not + /// underflow or panic. + #[test] + fn a_declaration_at_the_very_start_of_the_file_is_shown() { + let sub = "sub_pkg_marker foo;\nmodule sub (input logic clk);\nendmodule\n"; + // `foo` at offset 0 is not itself a declaration hover's target here; + // instead exercise the disk path with `def.name_span.start == 0` by + // hovering a module whose file begins with the keyword `module`. + let sub2 = "module sub (input logic clk);\nendmodule\n"; + let top = "module top;\n sub u (.clk(1'b0));\nendmodule\n"; + let (dir, ws, uri) = included("startdecl", &[("sub.sv", sub2), ("top.sv", top)]); + let body = text_of(&hover(&ws, &uri, at(top, "sub u")).expect("hover")); + assert!(body.contains("```systemverilog\nmodule sub"), "got {body}"); + let _ = fs::remove_dir_all(&dir); + let _ = sub; + } + + /// Angle 2: the declaration is on the last line of the file, which has no + /// trailing newline. `whole_lines`'s `line_range(last).end` must resolve + /// to the true end of text, not run past it or leave a dangling range. + #[test] + fn a_declaration_on_the_last_line_with_no_trailing_newline_is_shown() { + let sub = "module sub (input logic clk);\nendmodule"; // no trailing \n + let top = "module top;\n sub u (.clk(1'b0));\nendmodule\n"; + let (dir, ws, uri) = included("notrailingnl", &[("sub.sv", sub), ("top.sv", top)]); + let body = text_of(&hover(&ws, &uri, at(top, "sub u")).expect("hover")); + assert!(body.contains("```systemverilog\nmodule sub"), "got {body}"); + let _ = fs::remove_dir_all(&dir); + } + + /// Angle 3: the target file is open under a *different* `Uri` whose path + /// differs only in case from the index's recorded path (macOS/Windows + /// default to a case-insensitive filesystem, so this is the same file on + /// disk). `document_for_path` compares `PathBuf`s with `==`, which is + /// case-sensitive even on a case-insensitive filesystem, so the open + /// buffer is *not* found as "the target file open" and the code falls + /// back to the disk-read path. That fallback is exactly the safe + /// direction — it cannot show unsaved live edits, but it also cannot mix + /// up two differently-cased identities — so this is a documented + /// limitation, not a defect: an unsaved edit in a case-mismatched buffer + /// is invisible to hover until saved. + #[cfg(any(target_os = "macos", target_os = "windows"))] + #[test] + fn a_case_mismatched_open_buffer_is_not_recognized_as_the_target_falls_back_to_disk() { + let saved = "module sub (\n input logic [7:0] addr\n);\nendmodule\n"; + let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n"; + let (dir, mut ws, uri) = included("casefallback", &[("sub.sv", saved), ("top.sv", top)]); + // Open the same file via an upper-cased path. + let upper = dir.join("SUB.sv"); + let upper_uri = Uri::from_str(&format!("file://{}", upper.display())).expect("uri"); + let edited = "module sub (\n input logic [15:0] addr\n);\nendmodule\n"; + ws.set_document(upper_uri, edited.to_string()); + + let body = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover")); + // Disk (saved) text wins, not the case-mismatched buffer's edit — + // confirms the fallback direction is the safe one. + assert!(body.contains("[7:0] addr"), "got {body}"); + assert!(!body.contains("[15:0]"), "got {body}"); + let _ = fs::remove_dir_all(&dir); + } + + /// Angle 7 (perf smell): a hover resolving into a large *closed* file + /// reads the whole file from disk and builds a fresh `LineIndex` over it + /// — twice, once inside `locate::line_number` for the heading and once + /// inside `declaration_snippet` for the snippet, since neither shares the + /// other's read. Not a correctness bug (hover is a rare, single-shot + /// request, and `text_of`/`LineIndex::new` are linear), but a measurable, + /// avoidable doubling of I/O and scan work on every disk-path hover. + /// Ignored by default (it writes/reads ~30 MB and just measures); run + /// with `cargo test --release -p lucisv_server large_closed -- --ignored + /// --nocapture` to see the number. + #[test] + #[ignore = "perf measurement, not a correctness assertion — see QA log"] + fn hovering_into_a_large_closed_file_reads_it_twice() { + let dir = temp_dir("bigfile"); + let mut sub = String::from("module sub (\n input logic [7:0] addr\n);\n"); + for n in 0..600_000 { + sub.push_str(&format!(" // filler line {n} of a big netlist-shaped file\n")); + } + sub.push_str("endmodule\n"); + fs::write(dir.join("sub.sv"), &sub).expect("write"); + let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n"; + let top_path = dir.join("top.sv"); + fs::write(&top_path, top).expect("write"); + + let mut ws = Workspace::default(); + // The default `maxFileSize` is 1 MiB (`DEFAULT_MAX_FILE_SIZE`); a + // netlist-shaped file this size needs the cap raised or it is never + // indexed at all, which would make this measure nothing. + ws.set_client_settings(crate::settings::ClientSettings { + max_file_size: 100_000_000, + ..Default::default() + }); + ws.open_whole_workspace(vec![dir.clone()]); + let uri = path_to_uri(&top_path).expect("uri"); + ws.set_document(uri.clone(), top.to_string()); + + let start = std::time::Instant::now(); + let body = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover")); + let elapsed = start.elapsed(); + assert!(body.contains("[7:0] addr"), "got {body}"); + eprintln!( + "hover into a {:.1} MB closed file took {:?} (reads the file + builds a LineIndex twice)", + sub.len() as f64 / 1_000_000.0, + elapsed + ); + let _ = fs::remove_dir_all(&dir); + } +} diff --git a/crates/lucisv_server/src/nav.rs b/crates/lucisv_server/src/nav.rs index 1d7d114..b3b2b04 100644 --- a/crates/lucisv_server/src/nav.rs +++ b/crates/lucisv_server/src/nav.rs @@ -157,7 +157,11 @@ fn indexed_target(ws: &Workspace, doc: &Document, offset: u32) -> Option( +/// +/// Shared with `hover.rs`, which walks it the other way round — from an +/// indexed `Def` to the live symbol that is it — so a hover snippet is read at +/// the declaration's *live* span (`docs/features/hover-declarations/README.md`). +pub(crate) fn indexed_def_for_symbol<'a>( ws: &'a Workspace, doc: &Document, symbol: &Symbol, diff --git a/docs/features/hover-declarations/README.md b/docs/features/hover-declarations/README.md new file mode 100644 index 0000000..31255d9 --- /dev/null +++ b/docs/features/hover-declarations/README.md @@ -0,0 +1,329 @@ +# hover-declarations + +## Goal + +Hovering a name declared in **this** file has always shown the declaration +itself — `local_text` prints the kind, the name and the source lines +`decl_span` covers. Hovering a name declared in *another* file showed only +`**port** — declared in `sub.sv:3``: enough to navigate to, not enough to read. +The owner's ask (2026-08-27) is that the cross-file card carry the declaration +too — for a port its direction, type and width, `input logic [7:0] addr` — so +that reading a connection list does not require jumping out of the file. This +round adds a fenced `systemverilog` snippet of the declaration's source line(s) +under each candidate's existing heading, fetched at hover time and omitted +entirely whenever it could be the wrong line. + +## Assumptions + +- **The index stays text-free.** `Def` is `{file, name_span, kind}` and the + persisted facts and `FACTS_FORMAT` are untouched + (`docs/features/workspace-index/README.md`, + `docs/features/index-persistence/README.md`). A hover is a rare, one-name, + human-speed request; reading one file to answer it is the same trade + `locate::line_number` has always made for the `file:line` half of the card. +- **`reference.name` is the declared name.** Every `Definition::External` + answer comes from a reference (`ExternalResolutions::definition_of` looks the + target up by `ReferenceId`), and `resolve_external` finds the `Def` by + passing exactly that `name` to `WorkspaceIndex::units` / `member`. So the + name is the bare declared spelling — `WIDTH` for a `p::WIDTH` use, `clk` for + a `.clk(...)` connection — never a qualified path. That is what makes it + usable as the guard's expected text. +- **Disk text is what the index was built from.** `Workspace::text_of` prefers + an open buffer, which is right for a location and wrong for a snippet, so the + open case is handled separately and never reaches `text_of`. +- **A `decl_span` may be enormous.** A module's `decl_span` is its whole body + (`bind_module` passes the item span), and one netlist line has no bound at + all — hence the two caps below. + +## Handshakes + +**Consumed** + +- `crate::nav::indexed_def_for_symbol` — raised from private to `pub(crate)`, + behaviour byte-for-byte unchanged. `nav.rs` walks it live-symbol → indexed + `Def`; this feature walks the same relation the other way (scan the open + buffer's symbols for the one that maps to this `Def`), which is precisely + what `nav.rs`'s own `include_declaration` block already does for the + declaration location. One matcher, so a hover snippet and a + go-to-definition can never disagree about which declaration is which. +- `Workspace::document_for_path`, `Workspace::text_of`, `WorkspaceIndex::path`. +- `crate::convert::Positions::whole_lines`, `vlog_parser::LineIndex`. +- `vlog_semantic::{Def, Symbol}` — read only; nothing added to either. + +**Promised** + +- `nav.rs` keeps its behaviour: the visibility change is the only edit to it, + and its whole test module stays green unmodified. +- The `` ```systemverilog `` fence tag is used for the new block, as the + fence-tag contract in `docs/features/lucisv-server/README.md` requires — it + is the only thing that colours a hover card. +- Nothing is added to `Def`, to the facts file, or to `FACTS_FORMAT`; a cache + written before this round is still current after it. +- The heading line `**label** — declared in `file:line`` is unchanged, so a + client (or a test) reading only that half sees exactly what it saw before. + +## How the snippet is fetched + +`declaration_snippet(ws, def, name)` in `hover.rs`, once per candidate: + +1. **The target file is open** (`ws.document_for_path`). The index's span is + against that file's *last saved* text, so an unsaved edit above the + declaration has already moved it and reading the buffer at `def.name_span` + would print whatever those offsets now cover. Match the `Def` to a live + symbol **logically** instead — same name, and `indexed_def_for_symbol` maps + it back to this same `Def` — and widen that symbol's live `decl_span` to + whole lines. +2. **Not open**: `ws.text_of(path)` (disk, since no buffer backs it), a fresh + `LineIndex`, and `def.name_span` widened to whole lines. +3. **Guard, both paths.** Slice the chosen text at the chosen name span and + require it to equal the hovered name. `str::get` returns `None` for a span + that runs past the text or lands mid-character, so a stale or shifted span + fails the check rather than panicking. Any failure — unreadable file, no + live symbol, text that does not spell the name — drops the snippet and + leaves today's card exactly as it was. **A hover must never lie; less + information beats wrong information.** + +Note the asymmetry, and that it is deliberate: the open path widens +`decl_span` (mirroring `local_text`, which is the only span a live symbol +offers that covers a whole multi-line declaration), the disk path widens +`def.name_span` (the only span the index holds). For the declarations the ask +is about — ports, parameters, typedefs, a module header — both are one line +and the two paths print the same thing. + +## Cutting it down + +`cut_to_size` trims trailing blank space (as `local_text` does; leading +indentation stays, so the line reads as written) and then applies two caps, +each with its own note under the fence: + +| Cap | Value | Why | +|---|---|---| +| lines | `SNIPPET_LINES` = 5 | a module's `decl_span` is its whole body | +| characters | `SNIPPET_CHARS` = 400 | one netlist line can be megabytes | + +A cut appends ` …` inside the fence and `*shown to N lines*` / +`*shown to N characters*` after it — the same shape as the macro card's +`*truncated at N characters*`, so the two footnotes read as one convention. +The character cap counts `char`s and cuts on a boundary. + +## Status / TODO + +- [x] `declaration_snippet` with the open-buffer and disk paths. +- [x] Guard on both paths; snippet omitted on any mismatch. +- [x] Line and character caps with a note. +- [x] One snippet per candidate for an ambiguous name. +- [x] `indexed_def_for_symbol` shared with `nav.rs`, behaviour unchanged. +- [x] Tests (9 new, in `hover.rs`'s own test module). +- [x] Hover row + hover section in `docs/features/lucisv-server/README.md`. +- [x] `cargo fmt` / `cargo clippy --all-targets` / `cargo test --workspace`. +- Not done, deliberately: no facts/cache change, nothing in `vlog_semantic`, + no TODO.md edit (no existing checklist item covers this; §8's hover items + are all already checked, and inventing one is out of scope). + +## Work log + +### 2026-08-27 — dev + +- Read the brief, `hover.rs`, `nav.rs`, `state.rs` and `convert.rs`. Confirmed + the two facts the design rests on: `set_document` does **not** rebuild the + index (so an open buffer really can hold a span the index does not know + about — the case step 1 exists for), and `follow_one` looks a `Def` up by + `reference.name`, which is what licenses using that name as the guard's + expected text rather than trying to recover a name from `Def`. +- Added `declaration_snippet`, `live_symbol`, `span_text`, `fenced` and + `cut_to_size` to `hover.rs`, plus the two caps as consts. `symbol_hover`'s + `External` arm now appends the snippet to each candidate's part; the heading + it appends to is untouched. +- Raised `nav::indexed_def_for_symbol` to `pub(crate)` with a doc line naming + the second caller. No other change to `nav.rs`. +- Decision: the open path uses `decl_span` and the disk path `name_span`, + per the brief. Considered using `name_span` on both for symmetry — it would + make a big module's card one header line rather than five — but that would + drop the live-buffer case's only handle on a multi-line declaration, and the + line cap already bounds the damage. Recorded in *How the snippet is fetched* + so the asymmetry is a decision and not an accident. +- Decision: no fallback from the open path to disk text. If a file is open and + no live symbol matches, the buffer has been edited past the index and the + indexed span is exactly the thing that cannot be trusted; falling back would + re-introduce the wrong-line risk the guard exists to remove. +- Nine tests added (listed below). Ran the gates: fmt + clean, clippy `--all-targets` clean, `cargo test --workspace` green at 2372 + passed / 0 failed / 12 ignored. + +**Tests added** (all in `crates/lucisv_server/src/hover.rs`, `mod tests`): + +| Test | Pins | +|---|---| +| `a_cross_file_port_connection_shows_the_ports_own_declaration_line` | the ask: direction + type + width, and only that port's line | +| `a_cross_file_module_instance_shows_its_header_line` | the module header, disk path | +| `a_package_member_shows_its_declaration_line` | a `localparam` and a `typedef` through `import p::*` | +| `an_unsaved_edit_that_moved_the_declaration_is_read_at_its_live_span` | live line, not the stale-span line (asserts the *new* width and the absence of the old) | +| `a_stale_indexed_span_drops_the_snippet_rather_than_showing_the_wrong_line` | guard, disk half: file rewritten under a live index → no fence at all, heading intact | +| `an_open_buffer_that_no_longer_declares_the_name_drops_the_snippet` | guard, live half: the port renamed away in the buffer | +| `a_very_long_declaration_line_is_cut_with_a_note` | the character cap and its note | +| `a_declaration_spanning_many_lines_is_cut_at_the_line_limit` | the line cap, via an open module whose `decl_span` is its body | +| `two_files_declaring_one_name_each_get_their_own_snippet` | ambiguous name: both headings, both snippets | + +## QA log + +### 2026-08-27 — QA + +Read the brief, the dev's Work log, and `crates/lucisv_server/src/hover.rs` / +`nav.rs` in full. Ran the gates first (all green before any probing): `cargo +fmt --check` clean, `cargo clippy --all-targets --workspace -- -D warnings` +clean, `cargo test --workspace` green — 1173 passed / 0 failed / 12 ignored +(pre-existing) before this round's own probes were added. + +Then attacked `declaration_snippet`, `live_symbol`, `span_text` and +`cut_to_size` along the seven angles in the charter. Eight probe tests added +to a new `mod qa_hover_declarations` in `hover.rs` (one `#[ignore]`d perf +measurement); one real defect found and fixed with a ninth test pinning it. + +**Finding 1 — MEDIUM, fixed.** *The guard was a fixed-length substring check, +not a whole-identifier check, so an edit that only **extends** a name defeats +it.* `declaration_snippet`'s guard (`hover.rs:243` and `:252`, before the fix) +compared `span_text(text, span)` — a slice of exactly `name.len()` bytes at +the *old, recorded* offset — against `name`. `def.name_span`'s length is +whatever the name was when the index was last built; it does not grow if the +file is edited without a reindex. So: index built on `input logic [7:0] +addr;`, then the file is rewritten on disk to `input logic [7:0] addr2;` +*without* triggering a reindex (an ordinary edit-then-hover-before-save-event +race, exactly the staleness window this feature's guard exists for). The old +span still covers exactly the four bytes `"addr"` — a *prefix* of the new +`"addr2"` — so `span_text` returns `Some("addr")`, equals the hovered name, +and the guard passed. The card for `.addr(...)` then showed +`` input logic [7:0] addr2 `` under a heading that says `addr`'s declaration, +one line pretending to be a name it is not — exactly the masked-corruption +shape CLAUDE.md's invariant 4 is about, applied to this round's new safety +net rather than `verify.rs`. + - Repro (was a failing/panicking assertion, now a passing regression test): + `a_disk_edit_that_only_appends_to_the_name_defeats_the_guard`, + `hover.rs:1060`. + - Fix: added `spells_exactly` (`hover.rs:293`) and `continues_a_name` + (`hover.rs:306`), and switched both guard call sites + (`declaration_snippet`'s live and disk branches) to it. It keeps the + existing text-equality check and additionally requires that the + character immediately outside the span on either side (if any) is not an + identifier-continuation character (`[A-Za-z0-9_$]`) — turning a + prefix/suffix match back into a miss. Applied to *both* branches for one + guard, one guarantee, even though the live branch's `symbol.name_span` + (a token span from a fresh parse) could not actually suffer this — + `symbol.name == name` was already checked before the span comparison, so + the length always matched there. No behavior change for any span that is + a genuine whole identifier, which is every case the dev's 9 tests and the + existing corpus tests exercise — full `cargo test --workspace` stayed + green (1173 passed / 0 failed / 13 ignored, the 13th being this round's + own perf probe) after the fix. + - This does **not** close every staleness gap by design — a same-length + edit that changes an identifier into a different same-length identifier, + or that changes what a name's *kind* means without renaming it, is still + the accepted risk window the Assumptions section already names ("a hover + is a rare, one-name, human-speed request"). What the fix removes is + specifically the case where the *shown text visibly disagrees with the + name in the heading* — the one the guard's stated promise ("never show a + wrong line") is about. + +**Finding 2 — LOW, filed, not fixed.** *A CRLF file's multi-line snippet +keeps the embedded `\r` on every interior line, only the last one is +trimmed.* `cut_to_size` (`hover.rs`, unchanged by QA) calls `trim_end()` once +on the whole cut string, which strips a *trailing* `\r` (and `\n`) but not an +interior one before a kept newline. `local_text` (the in-file branch, +pre-existing, not part of this round) has the identical property via the same +`whole_lines`/`trim_end` shape, so this is not new behavior introduced by +this feature, just newly reachable from a second call site. Cosmetic, not a +correctness break: the bytes shown are exactly the file's own bytes, and a +fenced code block renders them close to verbatim either way. Pinned as a +permanent regression test rather than fixed, since a real fix (stripping +`\r` before every kept `\n`, in both `local_text` and here) is a +cross-cutting change to shared rendering, out of this round's stated scope +(`hover.rs`'s `External` arm and its shared helper with `nav.rs`). + - Repro: `a_crlf_multiline_snippet_keeps_interior_carriage_returns`, + `hover.rs:1156`. + +**Finding 3 — LOW/accepted, pinned as a regression test, not a defect of this +round.** *Two live declarations of the same name+kind in one open buffer (a +transient mid-edit state, e.g. a duplicate line not yet deleted) make +`live_symbol`'s `.find()` pick whichever comes first in `Semantics::symbols()` +order, silently.* `indexed_def_for_symbol` (`nav.rs:164`, visibility-only +change this round) maps *any* live symbol with a matching name/kind/owner +back to the single persisted `Def` for that name when the index itself has +only one — it does not know or care that the *live* buffer momentarily has +two. This is inherited, unchanged behavior from `nav.rs`'s existing +go-to-definition matcher (the Handshakes section calls this out on purpose: +"one matcher, so a hover snippet and a go-to-definition can never disagree"). +Not a lie in the sense the guard is about — the guard still requires the +*chosen* symbol's own span to spell the name exactly, which it always does +here by construction — but it is a silent, unsignaled choice between two +candidates. Filed rather than fixed: fixing it means changing +`indexed_def_for_symbol`'s matching rule, which is nav.rs's and explicitly +out of this round's scope ("nav tests must stay green," brief line 27). + - Repro: `duplicate_live_declarations_of_one_name_pick_the_first_one_silently`, + `hover.rs:1126`. + +**Finding 4 — perf note, not a defect, no action taken.** *A hover resolving +into a large closed file reads the file and builds a `LineIndex` over it +twice*: once inside `locate::line_number` (for the `file:line` heading — this +predates this round) and again inside `declaration_snippet` (for the +snippet — new this round), independently, from the same disk path. Measured +in release mode: a 31.7 MB synthetic file (600k filler lines behind a small +port declaration, `maxFileSize` raised so it indexes at all) took 34 ms for +one hover — acceptable for a rare, single-shot request, but a real, avoidable +doubling of I/O and linear scan work per disk-path candidate. A fix would +mean threading one read/`LineIndex` through both `line_number` and +`declaration_snippet`, which touches `locate.rs` (also used by `macro_hover`) +and is a small refactor rather than a one-line change — noted per the +charter's "note it, don't redesign" rather than attempted. + - Measurement, `#[ignore]`d (writes ~30 MB, not a correctness assertion): + `hovering_into_a_large_closed_file_reads_it_twice`, `hover.rs:1325`. Run + with `cargo test --release -p lucisv_server large_closed -- --ignored + --nocapture`. + +**Verified, no finding** (angles from the charter that turned up nothing): +UTF-8 multi-byte content before a declaration, on the same file, does not +panic `span_text`/`whole_lines` (`multibyte_utf8_before_the_declaration_does_not_panic`, +`hover.rs`) — both are `.get()`-based and this stayed a belt-and-braces pin. +A declaration at byte offset 0 and a declaration on the file's last line with +no trailing newline both render correctly, no underflow +(`a_declaration_at_the_very_start_of_the_file_is_shown`, +`a_declaration_on_the_last_line_with_no_trailing_newline_is_shown`). The line +cap (`SNIPPET_LINES` = 5) and character cap (`SNIPPET_CHARS` = 400) are both +exact-boundary-safe — 5 lines / 400 chars is not cut, 6 lines / 401 chars is, +and a 400-char boundary landing mid multi-byte character is not split because +`cut_to_size` counts with `char_indices`, never raw bytes +(`exactly_the_line_cap_is_not_cut_one_more_is`, +`exactly_the_char_cap_is_not_cut_one_more_is_and_boundary_is_safe`). A +case-mismatched open buffer (same file, different-case path on a +case-insensitive filesystem) is not recognized as "the target file open" by +`document_for_path`'s exact `PathBuf` equality, so it falls back to the disk +path rather than mixing the two identities — the safe direction, confirmed +with unsaved edits in the mismatched buffer never leaking into the card +(`a_case_mismatched_open_buffer_is_not_recognized_as_the_target_falls_back_to_disk`, +macOS/Windows-gated). Multiple ambiguous candidates each render from their +own file with no cross-contamination — the dev's own +`two_files_declaring_one_name_each_get_their_own_snippet` already covers +this and reads fine without a divider between candidates (each fenced block +is its own visual unit). + +**Gates, final.** `cargo fmt --check` clean. `cargo clippy --all-targets +--workspace -- -D warnings` clean. `cargo test --workspace`: 1173 passed / 0 +failed / 13 ignored (12 pre-existing + this round's one perf probe). + +## Review + +**2026-08-27 — lead.** Reviewed the full diff after QA's SHIP verdict; +gates re-run independently (fmt clean, clippy silent, 1173 server tests +green). The shape is right: no widening of persisted facts, snippets +fetched at hover time from whichever text the span is valid against +(live logical match through `nav.rs`'s one matcher, disk otherwise), +and a guard that prefers no snippet to a wrong one. QA's MEDIUM find — +the fixed-length substring guard passing on a name that had merely been +*extended* in place — is precisely the masked-corruption shape +invariant 4 exists for, applied correctly to a new forgiveness path +outside `verify.rs`; the `spells_exactly` boundary check closes it on +both the live and disk paths and the attack test pins it. The +deliberate asymmetry (live path shows `decl_span`, disk path the name's +line) is documented and bounded by the caps; the duplicate-live-symbol +tie-break is inherited from the shared matcher and correctly pinned +rather than re-designed. The CRLF interior-`\r` cosmetic and the +double-read of large closed files are accepted as filed. Accepted; +committed by the lead. diff --git a/docs/features/lucisv-server/README.md b/docs/features/lucisv-server/README.md index c23f95c..79d92c5 100644 --- a/docs/features/lucisv-server/README.md +++ b/docs/features/lucisv-server/README.md @@ -28,7 +28,7 @@ looks like language knowledge in here is a bug or a `Handshake` request. | `textDocument/semanticTokens/full` | `vlog_parser::tokenize` + `Semantics` | Delta-encoded, split at line boundaries. Stamped with a `resultId` since 2026-08-26, so a delta can name it. **Declined with an error on a buffer over `lucisv.largeFile.threshold`** (2026-08-27): VS Code marks a model whose document provider answered *anything* as complete and then never asks its range provider again, so an empty answer would cost a 100 MB file all of its colour — see `docs/features/large-file-mode/README.md` | | `textDocument/semanticTokens/range` | the same classification pass | The visible lines only, for the first paint of a large file. A **self-contained** answer: the tokens overlapping the range, kept whole, re-encoded from the start of the document. No `resultId` — a partial view is not what a delta is computed against. See `docs/features/semantic-tokens-delta/README.md`. On a buffer over `lucisv.largeFile.threshold` this is the **only** request that colours anything, and it lexes the window itself (0.25 ms for a viewport of a 100 MB file) rather than filtering a token stream that was never built | | `textDocument/semanticTokens/full/delta` | the same classification pass | What changed since the answer the client names: one edit replacing everything between the common prefix and the common suffix (the suffix capped so the two cannot overlap — identical lines of Verilog encode identically, which is exactly the trap). An id the server does not hold, including one from before a `didClose`, is answered in full. Same feature README | -| `textDocument/hover` | `DefineTable`, `Semantics`, `WorkspaceIndex`, `includes::IncludeGraph`, `expand` | Macro body, or declaration kind + snippet. A macro this file does not define is answered from the workspace: the definition it **reaches through its `` `include``s** when exactly one is reachable, and every candidate otherwise. A macro card also shows what the hovered use **expands to in one step** — the body with this call's arguments substituted — when that says more than the body already does; a nested `` `INNER`` is left as written, an argument count that does not match expands nothing, and several candidates expand nothing. See `docs/features/macro-expansion/README.md` | +| `textDocument/hover` | `DefineTable`, `Semantics`, `WorkspaceIndex`, `includes::IncludeGraph`, `expand` | Macro body, or declaration kind + snippet. A macro this file does not define is answered from the workspace: the definition it **reaches through its `` `include``s** when exactly one is reachable, and every candidate otherwise. A macro card also shows what the hovered use **expands to in one step** — the body with this call's arguments substituted — when that says more than the body already does; a nested `` `INNER`` is left as written, an argument count that does not match expands nothing, and several candidates expand nothing. See `docs/features/macro-expansion/README.md`. A **cross-file** answer carries the declaration's own source line(s) under its `file:line` heading — `input logic [7:0] addr`, not just where it lives — read at hover time from the live buffer when that file is open and from disk otherwise, and omitted whenever the text and the span disagree: `docs/features/hover-declarations/README.md` | | `textDocument/definition` | `includes::IncludeGraph`, then `Semantics`, then `ExternalResolutions` | A cursor on an `` `include`` line jumps to the resolved file's first byte; otherwise the in-file symbol table, then the workspace overlay, whose `Ambiguous` answer returns every location. See `docs/features/include-nav/README.md` | | `textDocument/typeDefinition` | `type_def`, then `nav::definition` | The same jump one token to the left: from a name to where its **type** is declared — a `typedef`, an `interface`, a `class`, or the module an instance name stands for. The tree says which declaration a position is in and where its type name is written; the answer is then `definition` of *that* name, so cross-file resolution, ambiguity and position conversion are all the ones F12 already uses. One hop on an alias chain, an empty list for a built-in. See `docs/features/type-definition/README.md` | | `textDocument/linkedEditingRange` | `linked`, over `Document.tree` | SV's closing labels, edited as one name: the cursor on either half of `module m ... endmodule : m` (and of `endfunction`/`endtask`/`endclass`/`endpackage`/`endinterface`/`endclocking`, a named `begin`/`fork`, a generate block, and the prefix-labelled `b : begin ... end : b`) answers **both** ranges plus the SV `wordPattern`. The pair comes off one AST node — `name_span` with `end_label_span` — never off a text match, so four identical names at two nesting levels still pair syntactically. Two `null`s on purpose: a closer with **no** label (nothing to co-edit, and this never offers to create one) and a **mismatched** one (the spec requires identical text; linking would silently rewrite broken code). Escaped identifiers are excluded. See `docs/features/linked-editing/README.md` | @@ -588,14 +588,29 @@ overlap trap and the round-trip property: (`docs/features/include-nav/README.md`). 2. **A reference** resolved in-file: the symbol's kind, its name, and the source lines its `decl_span` covers. -3. **A reference** answered only by the workspace overlay: the kind and name, - plus each target's file and line. +3. **A reference** answered only by the workspace overlay: the kind, each + target's file and line, and — since 2026-08-27 — **that declaration's own + source line(s)** beneath each heading. 4. **A declaration** the cursor is sitting on: its own kind, name and snippet. The snippet is `decl_span` widened to whole lines, so a declaration reads as it was written rather than starting mid-line. +**The cross-file snippet (case 3).** The index holds no file contents, so the +line is fetched per hover: from the **live buffer** when the target file is +open — matched to the indexed `Def` logically through +`nav::indexed_def_for_symbol`, because an unsaved edit above a declaration has +already moved the span the index recorded — and from disk otherwise, where the +recorded span is the one the index was built from. Either way the chosen text +is sliced at the chosen name span and required to spell the hovered name; on +any mismatch, unreadable file or unmatched buffer the snippet is dropped and +the card is exactly what it was before this feature. It is capped at 5 lines +and 400 characters (a module's `decl_span` is its whole body; a netlist line +has no bound), with a footnote naming whichever cap cut it. Rules, the +deliberate span asymmetry between the two paths, and the guard's attack tests: +`docs/features/hover-declarations/README.md`. + **A macro card has a second half since M14 (0.5.0).** Under the definition it shows what the hovered *use* expands to in one step — the body with this call's arguments substituted for the parameters — fenced identically, with a footnote @@ -617,8 +632,10 @@ registered for exactly that language id, and that grammar is the *only* thing that colours a hover card: semantic tokens cannot reach markdown, and VS Code resolves a fence's info string against the language registry rather than against the hovered document. Changing the tag, or fencing a new surface with a -different one, silently returns every card to flat grey. The three call sites -pin the exact fenced string in their own tests; the registration is pinned by +different one, silently returns every card to flat grey. Every call site — +`define_text`, `expansion_text`, `local_text`, the cross-file `fenced` and the +completion templates' documentation panel — pins the exact fenced string in its +own tests; the registration is pinned by `crates/lucisv_server/tests/grammar.rs`, which also holds the extension's keyword list to `vlog_parser::KEYWORDS`. Rationale and inventory: `docs/features/editor-packaging/README.md`.