Files
lucisv/crates/lucisv_server/src/hover.rs
T
lucioandClaude Fable 5 20567e1a7f
ci / checks (push) Successful in 40s
ci / corpus (push) Successful in 18s
The index carries every declaration's line, and hover stops re-reading files
The owner's first-level cache, realized on the carrier the index
already had: DeclLines (name line + detail line) on every Decl/Def,
computed at index time from the LineIndex the analysis already holds —
tens of KB for 20k modules, FACTS_FORMAT 3->4, old stores discarded
whole. A closed file's hover heading now costs zero I/O (it survives
the file being deleted), and the snippet's one remaining read is
served from a bounded FileView LRU (4 entries / 8 MiB, newest kept,
dropped on set_document/close/update_one/rebuild): repeat hovers into
a 12 MB file go 5.8 ms -> ~1 us, cross-file hover means 40/157 us ->
4.7/12.9 us. Ports ride the same member entries, so their lines came
free. Stale-disk edits leave heading and snippet stale together, the
spells_exactly guard still omits rather than lies, and QA pinned the
pair. Measured and filed, not fixed here: the first request of a
session waits 287-780 ms behind the startup scan (handshake for the
next round).

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-28 18:04:38 -07:00

1865 lines
85 KiB
Rust

//! `textDocument/hover`.
//!
//! Four things can be under the cursor, tried in this order: a macro usage, a
//! reference resolved in this file, a reference the workspace answered, and a
//! declaration itself. The order and the rendering rules are in
//! `docs/features/lucisv-server/README.md`.
//!
//! A macro card also shows what the hovered use expands to in one step, when
//! that is more than the body it already prints — `crate::expand` and
//! `docs/features/macro-expansion/README.md`.
use lsp_types::{Hover, HoverContents, MarkupContent, MarkupKind, Uri};
use vlog_parser::defines::Define;
use vlog_parser::token::Token;
use vlog_parser::{LineIndex, TextRange};
use vlog_semantic::{Def, Definition, FileId, Symbol};
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;
/// Hover text for the cursor at `offset`.
pub fn hover(ws: &Workspace, uri: &Uri, offset: u32) -> Option<Hover> {
let doc = ws.document(uri)?;
macro_hover(ws, doc, offset).or_else(|| symbol_hover(ws, doc, offset))
}
// ----------------------------------------------------------------------
// `define expansion
// ----------------------------------------------------------------------
/// A macro usage under the cursor: the file's own definition wins, then the
/// one it reaches through its `` `include``s, then the workspace's — **all**
/// of the workspace's, because outside the include graph picking one would be
/// a guess.
fn macro_hover(ws: &Workspace, doc: &Document, offset: u32) -> Option<Hover> {
let token = doc.token_at(offset).filter(|token| token.is_macro())?;
let name = macro_name(token)?;
if let Some(define) = doc.defines.latest(name) {
return Some(markdown(doc, define_text(name, define, None, Some(&token.text)), token.span));
}
let candidates = narrowed_to_the_include_graph(ws, doc, ws.index().find_define(name));
if candidates.is_empty() {
return Some(markdown(doc, format!("`` `{name} `` — no definition found"), token.span));
}
// The expansion follows the definition the card shows, so it is offered
// only where the card shows exactly one: with several candidates listed,
// expanding one of them would be picking a winner the lookup refused to
// pick.
let call = (candidates.len() == 1).then_some(token.text.as_str());
let mut parts = Vec::with_capacity(candidates.len());
for (file, define) in &candidates {
let where_ =
ws.index().path(*file).map(|path| match line_number(ws, path, define.span.start) {
Some(line) => format!("{}:{line}", display_name(path)),
None => display_name(path),
});
parts.push(define_text(name, define, where_, call));
}
let joined = if parts.len() == 1 {
parts.remove(0)
} else {
format!(
"`` `{name} `` is defined {} times\n\n---\n\n{}",
parts.len(),
parts.join("\n\n---\n\n")
)
};
Some(markdown(doc, joined, token.span))
}
/// The one definition this file actually *reaches*, when there is exactly
/// one, and every candidate otherwise.
///
/// The include graph is the only thing that can order two definitions of one
/// macro name, so where it has an unambiguous answer the hover shows that
/// answer alone. Where it does not — nothing reachable defines the name, or
/// several reachable files do — the honest all-candidates list from before
/// this feature stands: an empty include graph must never make hover worse
/// than it was (`docs/features/include-nav/README.md`).
fn narrowed_to_the_include_graph<'a>(
ws: &Workspace,
doc: &Document,
candidates: Vec<(FileId, &'a Define)>,
) -> Vec<(FileId, &'a Define)> {
if candidates.len() < 2 {
return candidates;
}
let reachable = crate::includes::reachable_from(ws, doc);
if reachable.is_empty() {
return candidates;
}
let narrowed: Vec<(FileId, &Define)> = candidates
.iter()
.filter(|(file, _)| ws.index().path(*file).is_some_and(|p| reachable.contains(p)))
.cloned()
.collect();
match narrowed.len() {
1 => narrowed,
_ => candidates,
}
}
/// The macro's name: the identifier after the backtick, argument list excluded.
fn macro_name(token: &Token) -> Option<&str> {
let rest = token.text.strip_prefix('`')?;
let end = rest.find(|c: char| !c.is_ascii_alphanumeric() && c != '_' && c != '$');
let name = match end {
Some(end) => &rest[..end],
None => rest,
};
if name.is_empty() {
None
} else {
Some(name)
}
}
/// One definition, rendered: its signature, its body, where it came from, and
/// — when `call` is the macro use under the cursor — what that use expands to
/// in one step.
fn define_text(name: &str, define: &Define, origin: Option<String>, call: Option<&str>) -> String {
let signature = match &define.params {
Some(params) => format!("`define {name}({})", params.join(", ")),
None => format!("`define {name}"),
};
let mut out = String::new();
if let Some(origin) = origin {
out.push_str(&format!("defined in `{origin}`\n\n"));
}
out.push_str("```systemverilog\n");
out.push_str(&signature);
if !define.body.is_empty() {
out.push(' ');
out.push_str(&define.body);
}
out.push_str("\n```");
if let Some(expansion) = call.and_then(|call| expand::single_step(call, define)) {
out.push_str(&expansion_text(&expansion));
}
out
}
/// The "expands to" half of a macro hover card: this call's arguments
/// substituted into the body, fenced exactly like the definition above it.
///
/// Two footnotes, both there so the card cannot be misread as a preprocessor's
/// output: what a remaining macro use means, and where a long body stopped.
fn expansion_text(expansion: &Expansion) -> String {
let mut out = String::from("\n\n**expands to**\n\n```systemverilog\n");
out.push_str(&expansion.text);
out.push_str("\n```");
if expand::has_macro_use(&expansion.text) {
out.push_str("\n\n*one step: a nested macro use is left as written*");
}
if expansion.truncated {
out.push_str(&format!("\n\n*truncated at {} characters*", expand::CAP));
}
out
}
// ----------------------------------------------------------------------
// declarations and references
// ----------------------------------------------------------------------
/// A reference or a declaration under the cursor.
fn symbol_hover(ws: &Workspace, doc: &Document, offset: u32) -> Option<Hover> {
let range = hovered_name_span(doc, offset)?;
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);
let path = ws.index().path(def.file).map(|p| p.to_path_buf());
let mut where_ = None;
let mut snippet = None;
if let Some(path) = path.as_ref() {
if ws.document_for_path(path).is_some() {
// The live path reads the open buffer — `live_symbol`
// resolves the current span, and its guards stay. The
// line comes from that buffer's own index rather than
// from `def.lines`, because the buffer may hold
// unsaved edits the index has not seen.
where_ = line_number(ws, path, def.name_span.start)
.map(|line| format!("{}:{line}", display_name(path)));
snippet = name.and_then(|name| declaration_snippet(ws, def, name));
} else {
// The heading costs nothing: the line was recorded
// when the file was indexed, from the same text the
// span came from (`vlog_semantic::DeclLines`). Only
// the snippet still wants the file's text, and that
// comes from the workspace's shared view — one read
// per file per generation, so a card naming one file
// twice, and the next hover into it, are both free.
where_ = Some(format!("{}:{}", display_name(path), def.lines.name));
snippet = name.zip(ws.file_view(path)).and_then(|(name, view)| {
spells_exactly(&view.text, def.name_span, name)
.then(|| {
fenced_sections(
&view.text,
&view.lines,
def.name_span,
def.detail_span,
)
})
.flatten()
});
}
}
let where_ = where_.unwrap_or_else(|| "the workspace".to_string());
let mut part = format!("**{label}** — declared in `{where_}`");
if let Some(snippet) = snippet {
part.push_str(&snippet);
}
parts.push(part);
}
Some(markdown(doc, parts.join("\n\n"), range))
}
}
}
/// A local declaration: what it is, and the lines it was written on — with
/// the comment that documents those lines attached (`attached_lines`). A
/// non-ANSI port is named in the header and *finished* in the body
/// (`input signed [31:0] data_in;`), so its card has two sections: the
/// header's, then the body's, each carrying its own comment.
fn local_text(doc: &Document, symbol: &Symbol) -> String {
let head = format!("**{}** `{}`\n\n", kind_label(symbol.kind), symbol.name);
let body = fenced_sections(&doc.text, &doc.line_index, symbol.decl_span, symbol.detail_span)
.unwrap_or_default();
format!("{head}{body}")
}
/// The fenced half of a hover card: one section for a declaration complete
/// where it is named, two — header, then body detail — for a non-ANSI split
/// port. Each section is the declaration's own lines plus its attached
/// comment, cut to card size independently.
fn fenced_sections(
text: &str,
index: &LineIndex,
primary: TextRange,
detail: Option<TextRange>,
) -> Option<String> {
let section = |span: TextRange| fenced(&attached_lines(text, index, span)).unwrap_or_default();
let first = section(primary);
let second = detail.map(section).filter(|s| !s.is_empty());
let joined = match second {
Some(second) if !first.is_empty() => format!("{first}\n\n{second}"),
Some(second) => second,
None => first,
};
(!joined.is_empty()).then_some(joined)
}
// ----------------------------------------------------------------------
// comments attached to a declaration
// ----------------------------------------------------------------------
/// The lines a declaration was written on, plus every comment that documents
/// it, in source order. The three sources are independent — a declaration can
/// carry all three at once:
///
/// * a comment on the declaration's own line is already in those lines;
/// * the comment-only lines directly **above** attach — the walk stops at the
/// first line that is not comment-only, so a line carrying another port
/// (and its trailing comment) never contributes;
/// * the comment-only lines directly **below** attach, provided nothing else
/// could claim them: the first line after the block must be one
/// `only_a_closer_on` positively recognises, or the end of the file.
///
/// Only `//` lines and `/* ... */` complete on one line count; the interior
/// of a multi-line block comment is indistinguishable from code without
/// lexing, and a hover card that guessed would be the wrong-line lie the
/// snippet guards exist to prevent.
fn attached_lines(text: &str, index: &LineIndex, span: TextRange) -> String {
let Some((first, last)) = section_lines(index, span) else {
return String::new();
};
let line = |n: u32| {
index
.line_range(n)
.and_then(|r| text.get(r.start as usize..r.end as usize))
// A line's range ends before its `\n` but *after* the `\r` a CRLF
// file puts in front of it, which would land in the middle of the
// card's fenced block. Display text only; the buffer is untouched.
.map(|line| line.strip_suffix('\r').unwrap_or(line))
};
let decl: Vec<&str> = (first..=last).map(|n| line(n).unwrap_or("")).collect();
let mut above: Vec<&str> = Vec::new();
let mut n = first.saturating_sub(1);
while n >= 1 && comment_only(line(n).unwrap_or("")) {
above.push(line(n).unwrap_or(""));
n -= 1;
}
let mut below: Vec<&str> = Vec::new();
let mut n = last + 1;
while comment_only(line(n).unwrap_or("")) {
below.push(line(n).unwrap_or(""));
n += 1;
}
// The guard on the below half: the block is this declaration's only when
// the line after it cannot be another declaration — a closer, or the end
// of the file, where nothing follows to claim it. Anything else, a
// wrapped declaration's bare `input` included, is another declaration's
// leading comment.
let claimed_by_nothing_else = match line(n) {
Some(next) => only_a_closer_on(next),
None => true,
};
if !claimed_by_nothing_else {
below.clear();
}
above.into_iter().rev().chain(decl).chain(below).collect::<Vec<_>>().join("\n")
}
/// The 1-based (first, last) line numbers a span's lines cover.
fn section_lines(index: &LineIndex, span: TextRange) -> Option<(u32, u32)> {
if span.end <= span.start {
return None;
}
let first = index.line_col(span.start).0;
let last = index.line_col(span.end - 1).0;
Some((first, last))
}
/// Whether a line is nothing but a comment.
fn comment_only(line: &str) -> bool {
let trimmed = line.trim();
trimmed.starts_with("//")
|| (trimmed.starts_with("/*") && trimmed.ends_with("*/") && trimmed.len() >= 4)
}
/// Whether a line carries nothing but a closer — the only shape that lets a
/// comment block above it belong to the declaration *before* it.
///
/// The question a below-comment asks is "could anything after this block
/// claim it?", and the only honest textual answer is a whitelist: a line is
/// safe when every word on it is a block terminator, which includes a line
/// with no words at all (`);`, a blank line, punctuation). Everything else —
/// a name, a direction keyword, the bare `input` a *wrapped* declaration
/// begins with — reads as another declaration and the comment stays with it.
///
/// The bias is the point. This is textual on purpose: the disk path of a
/// cross-file hover has no parse to ask, and only a false "another
/// declaration is here" is safe, because it merely declines to attach a
/// comment — the direction that cannot lie. A false "nothing here" shows one
/// declaration's comment on another's card, which is the one thing this
/// feature promises never to do.
fn only_a_closer_on(line: &str) -> bool {
let code = match line.find("//") {
Some(at) => &line[..at],
None => line,
};
code.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_' || c == '$'))
.filter(|word| !word.is_empty())
.all(is_closer_word)
}
/// The words that end a block a declaration can live in, and nothing else:
/// what a comment block below a *last* declaration is followed by.
fn is_closer_word(word: &str) -> bool {
matches!(word, "end" | "endmodule" | "endinterface" | "endtask" | "endfunction")
}
// ----------------------------------------------------------------------
// 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 an **open** buffer, fenced for the card.
///
/// The index holds spans, kinds and lines but no text
/// (`docs/features/workspace-index/README.md`), so the *source* is fetched
/// here, at hover time, from whichever text the span is actually valid
/// against. A closed file is served by `Workspace::file_view` in the caller
/// instead, so this function never touches the disk.
///
/// `None` — no snippet, today's card unchanged — wherever the two could
/// disagree: the span the live buffer 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<String> {
// 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.
let path = ws.index().path(def.file)?;
let target = ws.document_for_path(path)?;
let symbol = live_symbol(ws, target, def, name)?;
if !spells_exactly(&target.text, symbol.name_span, name) {
return None;
}
fenced_sections(
&target.text,
&target.line_index,
symbol.decl_span,
symbol.detail_span.or(def.detail_span),
)
}
/// The live symbol in an open buffer that *is* this indexed declaration.
///
/// Only the declarations spelling `name` are probed — `indexed_def_for_symbol`
/// is two index lookups per candidate, and every other symbol in the buffer
/// was going to fail the name test anyway. `symbols_named` hands them over in
/// declaration order, so the first-match tie-break between two live
/// declarations of one name is the one the old whole-buffer scan made.
fn live_symbol<'a>(
ws: &Workspace,
target: &'a Document,
def: &Def,
name: &str,
) -> Option<&'a Symbol> {
target
.semantics
.symbols_named(name)
.filter_map(|id| target.semantics.symbol(id))
.find(|symbol| 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<String> {
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<String>) {
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<TextRange> {
if let Some(reference) = doc.semantics.reference_at(offset) {
return Some(reference.name_span);
}
doc.semantics.symbol_at(offset).and_then(|id| doc.semantics.symbol(id)).map(|s| s.name_span)
}
/// A markdown hover card highlighting `span` in the hovered document.
fn markdown(doc: &Document, value: String, span: TextRange) -> Hover {
Hover {
contents: HoverContents::Markup(MarkupContent { kind: MarkupKind::Markdown, value }),
range: Some(doc.positions().range(span)),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::uri::path_to_uri;
use std::fs;
use std::path::PathBuf;
use std::str::FromStr;
fn document(text: &str) -> (Workspace, Uri) {
let uri = Uri::from_str("file:///rtl/m.sv").expect("uri");
let mut ws = Workspace::default();
ws.set_document(uri.clone(), text.to_string());
(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:?}"),
}
}
fn temp_dir(tag: &str) -> PathBuf {
let dir =
std::env::temp_dir().join(format!("lucisv_server_hover_{tag}_{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).expect("temp dir");
dir
}
#[test]
fn hovering_a_macro_usage_shows_its_body() {
let text = "`define WIDTH 8\nmodule m;\n wire [`WIDTH-1:0] a;\nendmodule\n";
let (ws, uri) = document(text);
let hover = hover(&ws, &uri, at(text, "[`WIDTH") + 2).expect("hover");
let body = text_of(&hover);
// The fence tag is load-bearing: it is the language id the extension
// registers its TextMate grammar for, and the only reason a hover card
// renders highlighted. Pinned here so a rename cannot pass silently.
assert!(body.contains("```systemverilog\n`define WIDTH 8\n```"), "got {body}");
}
#[test]
fn hovering_a_function_like_macro_shows_its_signature() {
let text = "`define MAX(a, b) ((a) > (b) ? (a) : (b))\nmodule m;\n wire x = `MAX(1, 2);\nendmodule\n";
let (ws, uri) = document(text);
let hover = hover(&ws, &uri, at(text, "`MAX(1")).expect("hover");
let body = text_of(&hover);
assert!(body.contains("`define MAX(a, b)"), "got {body}");
assert!(body.contains("? (a) : (b)"), "got {body}");
}
#[test]
fn hovering_a_call_shows_what_it_expands_to_in_one_step() {
let text = "`define MAX(a, b) ((a) > (b) ? (a) : (b))\nmodule m;\n wire x = `MAX(p, q+1);\nendmodule\n";
let (ws, uri) = document(text);
let body = text_of(&hover(&ws, &uri, at(text, "`MAX(p")).expect("hover"));
// The definition stays, and the expansion is added under it — same
// fence tag, since that is what colours a hover card (0.4.1).
assert!(body.contains("```systemverilog\n`define MAX(a, b) ((a) > (b) ? (a) : (b))\n```"));
assert!(
body.contains("**expands to**\n\n```systemverilog\n((p) > (q+1) ? (p) : (q+1))\n```"),
"got {body}"
);
assert!(!body.contains("one step:"), "nothing left unexpanded here: got {body}");
}
#[test]
fn a_plain_object_like_macro_gets_no_second_section() {
// Its expansion *is* its body, which the card already shows.
let text = "`define WIDTH 8\nmodule m;\n wire [`WIDTH-1:0] a;\nendmodule\n";
let (ws, uri) = document(text);
let body = text_of(&hover(&ws, &uri, at(text, "[`WIDTH") + 2).expect("hover"));
assert!(!body.contains("expands to"), "got {body}");
}
#[test]
fn an_object_like_macro_that_calls_another_shows_where_one_step_stopped() {
let text =
"`define BASE 4\n`define W `BASE + 1\nmodule m;\n wire [`W-1:0] a;\nendmodule\n";
let (ws, uri) = document(text);
let body = text_of(&hover(&ws, &uri, at(text, "[`W-") + 1).expect("hover"));
assert!(body.contains("**expands to**\n\n```systemverilog\n`BASE + 1\n```"), "got {body}");
assert!(body.contains("*one step: a nested macro use is left as written*"), "got {body}");
assert!(!body.contains("`define BASE 4"), "one step, not two: got {body}");
}
#[test]
fn a_call_whose_argument_count_is_wrong_keeps_todays_card_and_guesses_nothing() {
let text = "`define MAX(a, b) ((a) > (b) ? (a) : (b))\nmodule m;\n wire x = `MAX(p);\nendmodule\n";
let (ws, uri) = document(text);
let body = text_of(&hover(&ws, &uri, at(text, "`MAX(p")).expect("hover"));
assert!(body.contains("`define MAX(a, b)"), "the card is unchanged: got {body}");
assert!(!body.contains("expands to"), "got {body}");
}
#[test]
fn an_argument_may_carry_commas_and_strings_of_its_own() {
let text = "`define SHOW(a, b) $display(a, b)\nmodule m;\n initial `SHOW(\"x, y\", f(1, 2));\nendmodule\n";
let (ws, uri) = document(text);
let body = text_of(&hover(&ws, &uri, at(text, "`SHOW(\"")).expect("hover"));
assert!(
body.contains("```systemverilog\n$display(\"x, y\", f(1, 2))\n```"),
"the commas inside the string and the call did not split it: got {body}"
);
}
#[test]
fn a_long_body_is_truncated_with_a_note() {
let filler = "z".repeat(crate::expand::CAP + 100);
let text =
format!("`define BIG(a) a + {filler}\nmodule m;\n wire x = `BIG(1);\nendmodule\n");
let (ws, uri) = document(&text);
let body = text_of(&hover(&ws, &uri, at(&text, "`BIG(1")).expect("hover"));
assert!(
body.contains(" …\n```"),
"cut with an ellipsis: got {}",
&body[..200.min(body.len())]
);
assert!(
body.contains(&format!("*truncated at {} characters*", crate::expand::CAP)),
"and says so"
);
}
#[test]
fn the_expansion_follows_the_definition_the_card_narrowed_to() {
// M10's include narrowing picks `a.svh`; the expansion must be that
// definition's, not the other file's.
let text = "`include \"a.svh\"\nmodule top;\n wire x = `M(7);\nendmodule\n";
let (dir, ws, uri) = included(
"expandreach",
&[
("a.svh", "`define M(x) x + 1\n"),
("b.svh", "`define M(x) x + 2\n"),
("top.sv", text),
],
);
let body = text_of(&hover(&ws, &uri, at(text, "`M(7")).expect("hover"));
assert!(body.contains("a.svh:1"), "got {body}");
assert!(body.contains("**expands to**\n\n```systemverilog\n7 + 1\n```"), "got {body}");
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn several_candidate_definitions_expand_nothing() {
let text = "module top;\n wire x = `M(7);\nendmodule\n";
let (dir, ws, uri) = included(
"expandambiguous",
&[
("a.svh", "`define M(x) x + 1\n"),
("b.svh", "`define M(x) x + 2\n"),
("top.sv", text),
],
);
let body = text_of(&hover(&ws, &uri, at(text, "`M(7")).expect("hover"));
assert!(body.contains("is defined 2 times"), "got {body}");
assert!(!body.contains("expands to"), "no winner to expand: got {body}");
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn an_undefined_macro_says_so_rather_than_returning_nothing() {
let text = "module m;\n wire x = `NOPE;\nendmodule\n";
let (ws, uri) = document(text);
let hover = hover(&ws, &uri, at(text, "`NOPE")).expect("hover");
assert!(text_of(&hover).contains("no definition found"));
}
#[test]
fn a_workspace_define_is_found_when_this_file_does_not_define_it() {
let dir = temp_dir("define");
fs::write(dir.join("defs.svh"), "`define WIDTH 8\n").expect("write");
let top_path = dir.join("top.sv");
let top_text = "module top;\n wire [`WIDTH-1:0] a;\nendmodule\n";
fs::write(&top_path, top_text).expect("write");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![dir.clone()]);
let uri = path_to_uri(&top_path).expect("uri");
ws.set_document(uri.clone(), top_text.to_string());
let hover = hover(&ws, &uri, at(top_text, "`WIDTH")).expect("hover");
let body = text_of(&hover);
assert!(body.contains("`define WIDTH 8"), "got {body}");
assert!(body.contains("defs.svh:1"), "the file and line: got {body}");
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn several_workspace_definitions_are_all_listed() {
let dir = temp_dir("dupdefine");
fs::write(dir.join("a.svh"), "`define W 8\n").expect("write");
fs::write(dir.join("b.svh"), "`define W 16\n").expect("write");
let top_path = dir.join("top.sv");
let top_text = "module top;\n wire [`W-1:0] a;\nendmodule\n";
fs::write(&top_path, top_text).expect("write");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![dir.clone()]);
let uri = path_to_uri(&top_path).expect("uri");
ws.set_document(uri.clone(), top_text.to_string());
let body = text_of(&hover(&ws, &uri, at(top_text, "`W-")).expect("hover"));
assert!(body.contains("is defined 2 times"), "got {body}");
assert!(body.contains("`define W 8"), "got {body}");
assert!(body.contains("`define W 16"), "got {body}");
let _ = fs::remove_dir_all(&dir);
}
/// A workspace whose files are `files`, with `top.sv` opened.
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)
}
/// A `top.sv` using `` `W ``, with whatever include lines precede it.
fn top_using_w(includes: &str) -> String {
format!("{includes}module top;\n wire [`W-1:0] a;\nendmodule\n")
}
#[test]
fn one_hop_of_include_picks_the_definition_the_file_actually_reaches() {
// Two files define `W`; only one of them is included. Before the
// include graph this hover listed both and refused to choose.
let (dir, ws, uri) = included(
"reach1",
&[
("a.svh", "`define W 8\n"),
("b.svh", "`define W 16\n"),
("top.sv", &top_using_w("`include \"a.svh\"\n")),
],
);
let body = text_of(
&hover(&ws, &uri, at(&top_using_w("`include \"a.svh\"\n"), "`W-")).expect("hover"),
);
assert!(body.contains("`define W 8"), "the reachable one: got {body}");
assert!(!body.contains("`define W 16"), "and not the other: got {body}");
assert!(body.contains("a.svh:1"), "named with its origin: got {body}");
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn two_hops_of_include_reach_just_as_far() {
let text = top_using_w("`include \"mid.svh\"\n");
let (dir, ws, uri) = included(
"reach2",
&[
("mid.svh", "`include \"deep.svh\"\n"),
("deep.svh", "`define W 8\n"),
("elsewhere.svh", "`define W 16\n"),
("top.sv", &text),
],
);
let body = text_of(&hover(&ws, &uri, at(&text, "`W-")).expect("hover"));
assert!(body.contains("`define W 8") && body.contains("deep.svh:1"), "got {body}");
assert!(!body.contains("`define W 16"), "got {body}");
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn an_include_cycle_terminates_and_both_files_stay_reachable() {
let text = top_using_w("`include \"a.svh\"\n");
let (dir, ws, uri) = included(
"reachcycle",
&[
("a.svh", "`include \"b.svh\"\n"),
("b.svh", "`include \"a.svh\"\n`define W 8\n"),
("elsewhere.svh", "`define W 16\n"),
("top.sv", &text),
],
);
let body = text_of(&hover(&ws, &uri, at(&text, "`W-")).expect("hover"));
assert!(body.contains("`define W 8") && body.contains("b.svh:2"), "got {body}");
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn a_definition_nothing_includes_is_still_shown_when_it_is_all_there_is() {
// The fallback that must not regress: an unreachable definition is
// better than none, and a project that does not use `` `include`` at
// all sees exactly what it saw before this feature.
let text = top_using_w("");
let (dir, ws, uri) =
included("reachnone", &[("far.svh", "`define W 8\n"), ("top.sv", &text)]);
let body = text_of(&hover(&ws, &uri, at(&text, "`W-")).expect("hover"));
assert!(body.contains("`define W 8") && body.contains("far.svh:1"), "got {body}");
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn two_definitions_neither_of_them_reachable_are_still_both_listed() {
let text = top_using_w("`include \"empty.svh\"\n");
let (dir, ws, uri) = included(
"reachambiguous",
&[
("empty.svh", "// nothing here\n"),
("a.svh", "`define W 8\n"),
("b.svh", "`define W 16\n"),
("top.sv", &text),
],
);
let body = text_of(&hover(&ws, &uri, at(&text, "`W-")).expect("hover"));
assert!(body.contains("is defined 2 times"), "the honest answer: got {body}");
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn two_reachable_definitions_are_listed_rather_than_guessed_between() {
// The graph orders nothing here — both files are included — so the
// all-candidates answer stands.
let text = top_using_w("`include \"a.svh\"\n`include \"b.svh\"\n");
let (dir, ws, uri) = included(
"reachboth",
&[("a.svh", "`define W 8\n"), ("b.svh", "`define W 16\n"), ("top.sv", &text)],
);
let body = text_of(&hover(&ws, &uri, at(&text, "`W-")).expect("hover"));
assert!(body.contains("is defined 2 times"), "got {body}");
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn hovering_a_use_shows_its_declaration() {
let text = "module m;\n localparam WIDTH = 8;\n wire [WIDTH-1:0] a;\nendmodule\n";
let (ws, uri) = document(text);
let body = text_of(&hover(&ws, &uri, at(text, "[WIDTH") + 1).expect("hover"));
assert!(body.contains("**parameter**"), "got {body}");
// Fenced with the grammar's language id — see the macro hover test.
assert!(
body.contains("```systemverilog\n localparam WIDTH = 8;\n```"),
"the decl snippet: got {body}"
);
}
// ------------------------------------------------------------------
// non-ANSI split ports: two sections, each with its comment
// ------------------------------------------------------------------
const SPLIT: &str = "\
module alu (
// the operand
data_in,
result // the result
);
input signed [31:0] data_in; // 32-bit operand A
output reg [63:0] result;
endmodule
";
#[test]
fn a_split_port_hovers_as_two_sections_with_their_comments() {
// The same card from both places the port is declared: the header
// name and the body declaration.
let (ws, uri) = document(SPLIT);
for needle in ["data_in,", "data_in;"] {
let body = text_of(&hover(&ws, &uri, at(SPLIT, needle)).expect("hover"));
assert!(body.contains("**port** `data_in`"), "the heading: {needle:?} -> {body}");
// Section one: the header, with the comment-only line above it.
assert!(
body.contains("```systemverilog\n // the operand\n data_in,\n```"),
"the header section, comment attached: {needle:?} -> {body}"
);
// Section two: the body declaration, with its same-line comment.
assert!(
body.contains(
"```systemverilog\ninput signed [31:0] data_in; // 32-bit operand A\n```"
),
"the detail section, comment included: {needle:?} -> {body}"
);
// Two sections, not one merged block: two fences for one card.
assert!(
body.matches("```systemverilog").count() >= 2,
"two fenced sections: {needle:?} -> {body}"
);
}
}
#[test]
fn a_comments_below_a_declaration_attach_only_when_no_port_follows_them() {
// Below-comments attach when only the closer follows them (nothing
// else could they document)…
let below = "module alu (data_in);\ninput [7:0] data_in;\n// the operand\nendmodule\n";
let (ws, uri) = document(below);
let body = text_of(&hover(&ws, &uri, at(below, "data_in;")).expect("hover"));
assert!(
body.contains("input [7:0] data_in;\n// the operand"),
"a comment under the last declaration is attached: got {body}"
);
// …but a comment block sitting just above the *next* port's
// declaration is that port's leading comment, not this one's.
let stolen = "module alu (data_in, result);\ninput [7:0] data_in;\n// about result\noutput result;\nendmodule\n";
let (ws, uri) = document(stolen);
let body = text_of(&hover(&ws, &uri, at(stolen, "data_in,")).expect("hover"));
assert!(
!body.contains("// about result"),
"the next port's leading comment is not stolen: got {body}"
);
// …and it does reach the port it documents.
let body = text_of(&hover(&ws, &uri, at(stolen, "result;") + 1).expect("hover"));
assert!(body.contains("// about result"), "attached to its own port: got {body}");
}
#[test]
fn an_old_style_task_argument_hovers_as_two_sections_too() {
// QA, PDS-3: a task or function argument named in the header and
// finished in the body is the same split shape a module port is, and
// now gets the same two-section card.
let text = "\
module m;
// the operand
task t(a);
input [7:0] a; // 8 bits wide
$display(a);
endtask
endmodule
";
let (ws, uri) = document(text);
for needle in ["a);", "a; //"] {
let body = text_of(&hover(&ws, &uri, at(text, needle)).expect("hover"));
assert!(
body.contains("```systemverilog\n // the operand\n task t(a);\n```"),
"the header section: {needle:?} -> {body}"
);
assert!(
body.contains("```systemverilog\n input [7:0] a; // 8 bits wide\n```"),
"the body declaration's section: {needle:?} -> {body}"
);
}
}
#[test]
fn a_wrapped_next_declaration_keeps_its_own_leading_comment() {
// QA, PDS-1: the guard used to ask whether the line after a
// below-comment carried an identifier the port grammar could not
// account for. A declaration that *wraps*, with its direction keyword
// alone on the first line, carries no such identifier there — so the
// guard read "no other port here" and handed `result`'s comment to
// `data_in`. Only a line positively recognised as a closer may let a
// comment through now.
let wrapped = "\
module alu (data_in, result);
input [7:0] data_in;
// about result
input
[7:0] result;
endmodule
";
let (ws, uri) = document(wrapped);
let body = text_of(&hover(&ws, &uri, at(wrapped, "data_in;")).expect("hover"));
assert!(
!body.contains("// about result"),
"a wrapped next declaration's comment is not stolen: got {body}"
);
// …and it reaches the port it was written for, above its own lines.
let body = text_of(&hover(&ws, &uri, at(wrapped, "result;")).expect("hover"));
assert!(
body.contains("// about result\ninput\n [7:0] result;"),
"attached above the wrapped declaration it documents: got {body}"
);
}
#[test]
fn a_wrapped_declaration_keeps_the_comment_below_it() {
// The other half of PDS-1: a wrapped declaration that really is the
// last one still takes the comment under it, because what follows the
// comment is a closer.
let text = "\
module alu (data_in);
input
[7:0] data_in;
// the operand
endmodule
";
let (ws, uri) = document(text);
let body = text_of(&hover(&ws, &uri, at(text, "data_in;")).expect("hover"));
assert!(
body.contains("input\n [7:0] data_in;\n// the operand"),
"the last, wrapped declaration takes the comment below it: got {body}"
);
}
#[test]
fn a_declaration_shows_the_comments_above_beside_and_below_it_at_once() {
// The owner's rule reads the three sources independently: same line,
// above, below. QA, PDS-2 — the implementation used to run a priority
// chain, so an above-comment or a trailing one silently suppressed
// the block below even when nothing else could claim it.
let text = "\
module alu (data_in);
// above
input [7:0] data_in; // beside
// below
endmodule
";
let (ws, uri) = document(text);
let body = text_of(&hover(&ws, &uri, at(text, "data_in;")).expect("hover"));
assert!(
body.contains("// above\ninput [7:0] data_in; // beside\n// below"),
"all three comments, in source order: got {body}"
);
}
#[test]
fn a_header_port_shows_the_comments_above_and_below_it_at_once() {
// PDS-2's own repros, both in one header: an above-comment (repro 1)
// and a same-line trailing comment (repro 2) each used to suppress
// the block below, which only `);` follows.
let text = "\
module alu (
// above
data_in, // beside
// below
result
);
input [7:0] data_in;
input result;
endmodule
";
let (ws, uri) = document(text);
let body = text_of(&hover(&ws, &uri, at(text, "data_in,")).expect("hover"));
// `result` follows the block, so it is `result`'s comment, not this
// port's — the guard stays exactly as strict as it was.
assert!(!body.contains("// below"), "another port's comment is not stolen: got {body}");
assert!(
body.contains(" // above\n data_in, // beside"),
"above and beside both attach: got {body}"
);
// With nothing but the closer after it, the same block does attach.
let last = "\
module alu (
// above
data_in // beside
// below
);
input [7:0] data_in;
endmodule
";
let (ws, uri) = document(last);
let body = text_of(&hover(&ws, &uri, at(last, "data_in ")).expect("hover"));
assert!(
body.contains(" // above\n data_in // beside\n // below"),
"all three attach when only the closer follows: got {body}"
);
}
#[test]
fn the_line_above_a_header_port_does_not_leak_its_trailing_comment() {
// `result, // the result` above `data_in`'s own line: the line above
// carries another port, so its trailing comment stays result's.
let text = "\
module alu (
result, // the result
data_in
);
input [7:0] data_in;
endmodule
";
let (ws, uri) = document(text);
let body = text_of(&hover(&ws, &uri, at(text, "data_in\n")).expect("hover"));
assert!(!body.contains("the result"), "not the port above's comment: got {body}");
}
#[test]
fn a_cross_file_split_port_shows_both_sections() {
let sub = "module sub (\n addr,\n ready\n);\ninput logic [15:0] addr;\noutput ready;\nendmodule\n";
let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n";
let (dir, ws, uri) = included("splitx", &[("sub.sv", sub), ("top.sv", top)]);
let body = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover"));
assert!(
body.contains("```systemverilog\n addr,\n```"),
"the header section, from the index's spans: got {body}"
);
assert!(
body.contains("```systemverilog\ninput logic [15:0] addr;\n```"),
"the detail section, from the index's detail span: got {body}"
);
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn hovering_a_declaration_shows_its_own_info() {
let text = "module top;\n wire a;\nendmodule\n";
let (ws, uri) = document(text);
let body = text_of(&hover(&ws, &uri, at(text, "top")).expect("hover"));
assert!(body.contains("**module** `top`"), "got {body}");
}
#[test]
fn hovering_a_cross_file_module_names_its_file() {
let dir = temp_dir("xhover");
fs::write(dir.join("sub.sv"), "module sub (input clk);\nendmodule\n").expect("write");
let top_path = dir.join("top.sv");
let top_text = "module top;\n sub u (.clk(1'b0));\nendmodule\n";
fs::write(&top_path, top_text).expect("write");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![dir.clone()]);
let uri = path_to_uri(&top_path).expect("uri");
ws.set_document(uri.clone(), top_text.to_string());
let body = text_of(&hover(&ws, &uri, at(top_text, "sub u")).expect("hover"));
assert!(body.contains("**module**"), "got {body}");
assert!(body.contains("sub.sv:1"), "got {body}");
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_closed_files_heading_line_comes_from_the_index_and_not_from_a_read() {
// The round's central claim: `file:line` for an indexed declaration is
// `Def::lines`, recorded when the file was scanned, so the heading
// costs no read at all. Proved by removing the file from under the
// index — a heading that still names the line cannot have read it.
let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n";
let (dir, ws, uri) = included("headingfromindex", &[("sub.sv", PORTS), ("top.sv", top)]);
fs::remove_file(dir.join("sub.sv")).expect("remove");
let body = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover"));
assert!(body.contains("**port** — declared in `sub.sv:2`"), "got {body}");
// The snippet is the half that really wanted the text, and it is
// dropped rather than guessed at — exactly as it always was for a
// file that cannot be read.
assert!(!body.contains("```systemverilog"), "no snippet without text: got {body}");
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn a_second_hover_into_one_closed_file_reads_nothing() {
// The other half: the snippet's read is shared through
// `Workspace::file_view`, so the file is read once and the next hover
// into it — the same card, or another name in the same file — is
// served from what that read left behind. Observed the only honest
// way: rewrite the file behind the server's back and require the
// second card to be the first one. Stale text can only ever *omit* a
// snippet (the `spells_exactly` guard), never show a wrong line.
let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n";
let (dir, ws, uri) = included("viewshared", &[("sub.sv", PORTS), ("top.sv", top)]);
let first = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover"));
assert!(first.contains("input logic [7:0] addr"), "premise: got {first}");
fs::write(dir.join("sub.sv"), "module sub (\n input logic [15:0] addr\n);\nendmodule\n")
.expect("write");
let second = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover"));
assert_eq!(second, first, "the second hover did not read the file again");
let _ = fs::remove_dir_all(&dir);
}
/// QA (2026-08-28): the staleness window the README's Assumptions section
/// claims — "a line is a fact about the same snapshot the span is... where
/// the file has changed on disk with nothing telling the server, both are
/// stale together" — reproduced rather than taken on faith, and in the
/// one shape that could actually disagree: the index was built from the
/// *original* `sub.sv`, but `sub.sv` is rewritten on disk — no `didSave`,
/// no watcher event, no `update_one`/`rebuild_index` call, so the index is
/// never told — **before the view cache ever reads it**, so the first
/// hover's disk read sees the *new* bytes under the *old* span and offset.
/// The heading must still show the line the index recorded at the last
/// scan (stale, not a fresh-read line the index never computed), and the
/// snippet, reading the genuinely current text, must find the old span no
/// longer spells `addr` there and drop itself via `spells_exactly` rather
/// than show whatever now sits at that byte range.
#[test]
fn an_unreindexed_disk_edit_leaves_a_stale_heading_and_no_wrong_snippet() {
let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n";
let (dir, ws, uri) = included("staleheading", &[("sub.sv", PORTS), ("top.sv", top)]);
// Edited behind the server's back, before any hover has read this
// file at all: four lines inserted above the module, so `addr`'s true
// line is now 6 — and the byte offset the index still holds for it
// (from the *original* `sub.sv`) now lands inside a comment, not
// `addr`. The view cache is empty for this path, so the hover below
// is a genuinely fresh disk read of the edited bytes.
fs::write(
dir.join("sub.sv"),
"// one\n// two\n// three\n// four\nmodule sub (\n input logic [7:0] addr,\n\
\x20 output logic ready\n);\nendmodule\n",
)
.expect("write");
let after = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover"));
assert!(
after.contains("**port** — declared in `sub.sv:2`"),
"the heading must show the line the index recorded, not the file's true current \
line (6), until something reindexes it: got {after}"
);
assert!(
!after.contains("```systemverilog"),
"the snippet must be dropped, not show the comment the stale span now lands on: \
got {after}"
);
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";
let (ws, uri) = document(text);
assert!(hover(&ws, &uri, at(text, "\n\n") + 1).is_none());
}
#[test]
fn a_macro_name_stops_at_its_argument_list() {
let text = "`define M(a) a\nmodule m;\n wire x = `M(1);\nendmodule\n";
let (ws, uri) = document(text);
let doc = ws.document(&uri).expect("open");
let token = doc.tokens.iter().find(|t| t.is_macro()).expect("a macro usage token");
assert_eq!(macro_name(token), Some("M"));
}
}
/// QA (M10 include-nav): a defect pinned rather than fixed — see the QA log
/// in `docs/features/include-nav/README.md` for the writeup and the fix
/// options weighed there.
#[cfg(test)]
mod qa_findings {
use super::*;
use crate::settings::ClientSettings;
use crate::uri::path_to_uri;
use std::fs;
/// The angled form is correctly wired into the narrowing overlay: not a
/// finding, recorded as a permanent regression test since the six tests
/// the dev shipped in this file only exercise the quoted form.
#[test]
fn an_angled_include_narrows_hover_same_as_a_quoted_one() {
let dir = std::env::temp_dir().join(format!("lucisv_qa_hover_sys_{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(dir.join("inc")).expect("mkdir");
fs::write(dir.join("inc/uvm_macros.svh"), "`define W 8\n").expect("write");
fs::write(dir.join("elsewhere.svh"), "`define W 16\n").expect("write");
let top_path = dir.join("top.sv");
let top_text = "`include <uvm_macros.svh>\nmodule top;\n wire [`W-1:0] a;\nendmodule\n";
fs::write(&top_path, top_text).expect("write");
fs::write(dir.join("files.f"), "+incdir+inc\ntop.sv\ninc/uvm_macros.svh\nelsewhere.svh\n")
.expect("write");
let mut ws = Workspace::default();
ws.set_client_settings(ClientSettings {
filelist: Some(dir.join("files.f").display().to_string()),
..Default::default()
});
ws.open_whole_workspace(vec![dir.clone()]);
let uri = path_to_uri(&top_path).expect("uri");
ws.set_document(uri.clone(), top_text.to_string());
let h = hover(&ws, &uri, top_text.find("`W-").expect("needle") as u32).expect("hover");
let body = match &h.contents {
HoverContents::Markup(m) => m.value.clone(),
_ => panic!("markup"),
};
assert!(body.contains("`define W 8") && body.contains("uvm_macros.svh:1"), "got {body}");
assert!(!body.contains("`define W 16"), "got {body}");
let _ = fs::remove_dir_all(&dir);
}
/// QA finding (M10, HIGH), fixed 2026-08-25. On a case-insensitive
/// filesystem (the default on macOS — this machine — and on Windows)
/// `Path::is_file` succeeds for a case-mismatched candidate, and
/// `normalize` only folds `.`/`..`, so `IncludeGraph::resolve` used to
/// return the path *as written* in the `` `include ``. `WorkspaceIndex`
/// meanwhile records the file under the case that was read off disk, so
/// the two spellings were different `PathBuf`s and
/// `narrowed_to_the_include_graph`'s `reachable.contains(p)` check
/// silently missed a file that **is** genuinely reachable.
///
/// Below, `top.sv` includes both `defs.svh` (case-mismatched: the file is
/// `Defs.svh`) and `other.svh` (spelled correctly), and both are equally
/// reachable in truth. Two reachable definitions must fall back to the
/// honest "defined 2 times" answer — the same thing
/// `two_reachable_definitions_are_listed_rather_than_guessed_between`
/// above pins for the case-matched spelling. Before the fix this narrowed
/// to the correctly-cased file alone and showed it with full confidence,
/// which is "may only narrow, never widen" failing in the one direction
/// that matters. `IncludeGraph::as_the_index_spells_it` now re-spells a
/// resolved path to the index's own when exactly one in-scope file
/// matches it case-insensitively.
///
/// Case-gated: only macOS/Windows default to a case-insensitive
/// filesystem, so only there does the premise (`is_file` succeeding for
/// the wrong case) hold.
#[cfg(any(target_os = "macos", target_os = "windows"))]
#[test]
fn a_case_mismatched_include_still_counts_as_reachable() {
let dir = std::env::temp_dir().join(format!("lucisv_qa_hover_case_{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).expect("mkdir");
fs::write(dir.join("Defs.svh"), "`define W 8\n").expect("write");
fs::write(dir.join("other.svh"), "`define W 16\n").expect("write");
let top_path = dir.join("top.sv");
let top_text = "`include \"defs.svh\"\n`include \"other.svh\"\nmodule top;\n \
wire [`W-1:0] a;\nendmodule\n";
fs::write(&top_path, top_text).expect("write");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![dir.clone()]);
let uri = path_to_uri(&top_path).expect("uri");
ws.set_document(uri.clone(), top_text.to_string());
let h = hover(&ws, &uri, top_text.find("`W-").expect("needle") as u32).expect("hover");
let body = match &h.contents {
HoverContents::Markup(m) => m.value.clone(),
_ => panic!("markup"),
};
// Both files are reachable, so neither may be dropped and neither may
// be presented as the answer.
assert!(body.contains("is defined 2 times"), "got {body}");
assert!(body.contains("`define W 8") && body.contains("Defs.svh:1"), "got {body}");
assert!(body.contains("`define W 16") && body.contains("other.svh:1"), "got {body}");
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 used to keep the
/// `\r` on every line except the last, where `cut_to_size`'s `trim_end`
/// stripped it — an embedded control character in the middle of a fenced
/// block. QA filed it (hover-declarations finding 2, port-detail-spans
/// PDS-4); `attached_lines` now strips the carriage return as it composes
/// each line, so the fence holds `\n`-separated lines whatever the file's
/// line endings are. Display text only: nothing writes to the buffer.
#[test]
fn a_crlf_multiline_snippet_carries_no_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('\r'), "no carriage return survives into the card: got {body:?}");
assert!(
body.contains("module wide (\n input logic a\n);\n wire w0;"),
"the lines read as written, joined with plain newlines: 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): the **first** hover resolving into a large
/// *closed* file reads the whole file from disk and builds a fresh
/// `LineIndex` over it. It once did that twice — heading and snippet
/// independently — then once, through a per-hover memo, and since
/// `hover-line-index` (2026-08-28) it does it once *per file per
/// generation of that file*: the heading no longer wants any text at all
/// (`Def::lines`), and the snippet's read is held in
/// `Workspace::file_view` for the next hover. So this number is the first
/// touch, which is the one that still costs; the repeat is measured in
/// `perf::hovering_into_a_big_closed_file_first_touch_and_repeat`. Not a
/// correctness assertion, just the number; run with `cargo test --release
/// -p lucisv_server large_closed -- --ignored --nocapture` to see it.
#[test]
#[ignore = "perf measurement, not a correctness assertion — see QA log"]
fn hovering_into_a_large_closed_file_reads_it_once() {
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}");
let start = std::time::Instant::now();
let _ = hover(&ws, &uri, at(top, "addr(8")).expect("hover");
let again = start.elapsed();
eprintln!(
"hover into a {:.1} MB closed file took {:?} the first time (one read + one \
LineIndex, for the snippet alone) and {:?} the second (nothing read)",
sub.len() as f64 / 1_000_000.0,
elapsed,
again
);
let _ = fs::remove_dir_all(&dir);
}
}