Compare commits

...
4 Commits
Author SHA1 Message Date
lucioandClaude Fable 5 94b130aca1 Release 0.12.1 — hover shows the declaration itself
ci / checks (push) Successful in 48s
ci / corpus (push) Successful in 22s
release / build-and-publish (push) Successful in 5m0s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-27 22:35:56 -07:00
lucioandClaude Fable 5 efe67bde65 Hover shows the cross-file declaration itself, not just where it lives
ci / checks (push) Successful in 48s
ci / corpus (push) Successful in 21s
The Definition::External card now renders the declaration's source
line(s) fenced under the "declared in file:line" heading — direction,
type and width for a port, the header line for a module, the
declaration line for package members. No facts change: snippets are
fetched at hover time, from the live buffer via nav's logical matcher
when the target is open, from disk (what the index was built from)
otherwise. A boundary-checking guard (spells_exactly) drops the
snippet rather than ever showing a wrong line — QA's attack proved
prefix matching alone was forgivable (addr vs addr2) and the fix is
pinned. Caps at 5 lines / 400 chars with notes. 18 new tests.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-27 22:32:59 -07:00
lucioandClaude Fable 5 e70d979e51 Release 0.12.0 — the indexed-navigation release
ci / checks (push) Successful in 46s
ci / corpus (push) Successful in 21s
release / build-and-publish (push) Successful in 4m58s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-27 21:39:02 -07:00
lucioandClaude Fable 5 b2d778eb8d Indexed references: postings replace the per-request refactor walk
textDocument/references now reads declaration-to-occurrence postings
merged in WorkspaceIndex from compact per-file reference facts, with
open buffers overlaying live semantics — 0.062 ms/request over 820
files vs 21.7 ms for the old Workspace::sources() walk (~350x). The
walk stays as rename's engine and the equivalence oracle in tests.
FACTS_FORMAT 1->2 discards v1 caches whole. Cursor lookups
(symbol_at/reference_at/token_at) and macro-define lookup move to
binary-searched sorted tables; include definition inspects only the
cursor's line. Ambiguity refusals preserved throughout.

External dev: codex. Lead-reviewed, gates re-run, probe reproduced.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-27 21:36:01 -07:00
20 changed files with 1868 additions and 100 deletions

No files matched your search

+44
View File
@@ -4,6 +4,50 @@ All notable changes to lucisv are recorded here. Versions follow
[semantic versioning](https://semver.org/); until 1.0 the CLI's exit codes
(see `README.md`) are the only frozen contract.
## 0.12.1 — 2026-08-27
Hover shows the cross-file declaration itself. A name declared in
another file — a port at an instantiation, a module instance, a package
member — now renders its declaration's source line, fenced and
highlighted, under the existing "declared in `file:line`" heading:
direction, type and width for a port, the header line for a module.
Snippets come from the live buffer when the declaring file is open
(unsaved edits included) and from disk otherwise, with a
boundary-checking guard that drops the snippet rather than ever
showing a wrong line, and caps of 5 lines / 400 characters for
netlist-sized declarations. No settings and no index format change.
## 0.12.0 — 2026-08-27
The indexed-navigation release: find-all-references stops paying a
project scan per request.
### References become a lookup
Each indexed file now persists compact reference facts — same-file uses
of its exported declarations, plus unresolved cross-file candidates —
and the workspace index resolves them once into
declaration-to-occurrence postings. `textDocument/references` reads
that posting list and overlays every open buffer's live analysis, so
unsaved additions, deletions and moved declarations stay visible with
no request-time scan: **0.06 ms per request over an 820-file workspace
where the old walk cost 22 ms (~350×)**. The old walk remains rename's
engine and is pinned equal to the indexed answer by test; ambiguity
still degrades to the in-file answer exactly as before.
### Cursor lookups stop sweeping
Declaration, reference and macro-token lookups under the cursor —
hover, definition, references entry points — binary-search sorted
position tables instead of scanning every symbol in the buffer, and
`` `include`` definition inspects only the cursor's line.
### One-time cache rebuild
The persisted facts format moved to version 2 for the new reference
records. An existing index cache from 0.11.0 is discarded whole on
first open and rebuilt — one re-scan, never a misread record.
## 0.11.0 — 2026-08-27
The large-workarea release: a project too big to scan is now a project
Generated
+8 -8
View File
@@ -97,7 +97,7 @@ dependencies = [
[[package]]
name = "lucisv"
version = "0.11.0"
version = "0.12.1"
dependencies = [
"lucisv_core",
"rayon",
@@ -108,11 +108,11 @@ dependencies = [
[[package]]
name = "lucisv_core"
version = "0.11.0"
version = "0.12.1"
[[package]]
name = "lucisv_server"
version = "0.11.0"
version = "0.12.1"
dependencies = [
"lsp-server",
"lsp-types",
@@ -248,14 +248,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "vlog_formatter"
version = "0.11.0"
version = "0.12.1"
dependencies = [
"vlog_parser",
]
[[package]]
name = "vlog_linter"
version = "0.11.0"
version = "0.12.1"
dependencies = [
"vlog_formatter",
"vlog_parser",
@@ -264,11 +264,11 @@ dependencies = [
[[package]]
name = "vlog_parser"
version = "0.11.0"
version = "0.12.1"
[[package]]
name = "vlog_refactor"
version = "0.11.0"
version = "0.12.1"
dependencies = [
"vlog_parser",
"vlog_semantic",
@@ -276,7 +276,7 @@ dependencies = [
[[package]]
name = "vlog_semantic"
version = "0.11.0"
version = "0.12.1"
dependencies = [
"vlog_parser",
]
+1 -1
View File
@@ -12,7 +12,7 @@ members = [
]
[workspace.package]
version = "0.11.0"
version = "0.12.1"
authors = ["Guoliang Chen"]
edition = "2021"
license = "MIT"
+649 -4
View File
@@ -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;
@@ -35,7 +37,7 @@ pub fn hover(ws: &Workspace, uri: &Uri, offset: u32) -> Option<Hover> {
/// 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.tokens.iter().find(|t| t.is_macro() && t.span.contains(offset))?;
let token = doc.token_at(offset).filter(|token| token.is_macro())?;
let name = macro_name(token)?;
if let Some(define) = doc.defines.latest(name) {
@@ -172,6 +174,11 @@ fn symbol_hover(ws: &Workspace, doc: &Document, offset: u32) -> Option<Hover> {
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<Hover> {
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<String> {
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<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) {
@@ -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);
}
}
+8 -1
View File
@@ -332,7 +332,14 @@ pub fn document_links(ws: &Workspace, uri: &Uri) -> Vec<DocumentLink> {
/// The same computation the links use, so F12 and ctrl-click can never
/// disagree about where a line goes.
pub fn definition(ws: &Workspace, doc: &Document, offset: u32) -> Option<Location> {
let (_, path) = resolved(ws, doc).into_iter().find(|(inc, _)| inc.span.contains(offset))?;
// Definition is a cursor request, so inspect only its line. `documentLink`
// still scans the whole file because it must return every include.
let (line, _) = doc.line_index.line_col(offset);
let line = doc.line_index.line_range(line)?;
let text = doc.text.get(line.as_range())?;
let include =
include_on_line(text, line.start).filter(|include| include.span.contains(offset))?;
let path = ws.includes().resolve(doc.path.as_deref(), &include)?;
Some(Location { uri: path_to_uri(&path)?, range: Range::default() })
}
+261 -23
View File
@@ -2,9 +2,10 @@
//! `textDocument/documentHighlight`.
use lsp_types::{DocumentHighlight, DocumentHighlightKind, Location, Uri};
use vlog_parser::TextRange;
use vlog_semantic::{Definition, Semantics, SymbolId};
use vlog_parser::{LineIndex, TextRange};
use vlog_semantic::{Def, Definition, ExternalTarget, Semantics, Symbol, SymbolId};
use crate::convert::Positions;
use crate::includes;
use crate::locate::location;
use crate::state::{Document, Workspace};
@@ -58,17 +59,11 @@ fn path_to_uri_or_self(ws: &Workspace, uri: &Uri) -> Option<Uri> {
/// Find-all-references, across the workspace when the symbol can leave this
/// file and inside it when it cannot.
///
/// The two paths answer the same question at very different prices: the
/// in-file answer is a lookup in an analysis the buffer already carries, and
/// the workspace answer re-reads and re-analyzes every in-scope file. So the
/// gate below is asked first, and it is asked of the *index* — a name it does
/// not hold as a unit or as an exported member cannot be named from another
/// file, so a local `wire` never starts a workspace walk.
///
/// The cross-file collection is `vlog_refactor`'s, the same one a rename runs
/// (`docs/features/references-nav/README.md`). When it declines — an
/// ambiguous name, a use nothing resolves — the file's own answer is sent
/// rather than an error: a highlight the editor can draw beats a shrug.
/// The cross-file path is an in-memory declaration-to-occurrence lookup in the
/// workspace index. Open buffers overlay their live semantics on those saved
/// postings, so unsaved additions and deletions remain visible without a
/// project scan. When the index declines an ambiguous target, the file's own
/// answer is sent rather than an error.
pub fn references(
ws: &Workspace,
uri: &Uri,
@@ -77,8 +72,10 @@ pub fn references(
) -> Vec<Location> {
let Some(doc) = ws.document(uri) else { return Vec::new() };
if leaves_this_file(ws, doc, offset) {
if let Some(locations) = workspace_references(ws, doc, offset, include_declaration) {
return locations;
if let Some(target) = indexed_target(ws, doc, offset) {
if let Some(locations) = indexed_references(ws, target, include_declaration) {
return locations;
}
}
}
in_file_references(ws, doc, uri, offset, include_declaration)
@@ -120,17 +117,168 @@ fn leaves_this_file(ws: &Workspace, doc: &Document, offset: u32) -> bool {
}
}
/// The workspace-wide answer, or `None` when the engine declined it.
fn workspace_references(
ws: &Workspace,
#[derive(Clone)]
struct IndexedTarget {
def: Def,
name: String,
declaration_path: std::path::PathBuf,
declaration_span: TextRange,
}
/// Map the live cursor answer onto the stable declaration held by this index.
fn indexed_target(ws: &Workspace, doc: &Document, offset: u32) -> Option<IndexedTarget> {
match doc.external.definition_of(&doc.semantics, offset)? {
Definition::Local(symbol) => {
let def = indexed_def_for_symbol(ws, doc, symbol)?.clone();
let declaration_path = doc.path.clone()?;
Some(IndexedTarget {
def,
name: symbol.name.clone(),
declaration_path,
declaration_span: symbol.name_span,
})
}
Definition::External([def]) => {
let id = doc.semantics.reference_id_at(offset)?;
let name = doc.semantics.reference(id)?.name.clone();
let declaration_path = ws.index().path(def.file)?.to_path_buf();
Some(IndexedTarget {
def: def.clone(),
name,
declaration_path,
declaration_span: def.name_span,
})
}
Definition::External(_) => None,
}
}
/// The indexed declaration represented by one live single-file symbol.
///
/// Matching is logical (path, owner, name and kind), not positional: edits
/// above a declaration may move its live span before the next save.
///
/// 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,
offset: u32,
symbol: &Symbol,
) -> Option<&'a Def> {
let path = doc.path.as_deref()?;
let file = ws.index().file_id(path)?;
let defs = if symbol.scope == doc.semantics.file_scope() {
ws.index().units(&symbol.name)
} else {
let owner = doc
.semantics
.scope(symbol.scope)
.and_then(|scope| scope.owner)
.and_then(|owner| doc.semantics.symbol(owner))?;
ws.index().member(&owner.name, &symbol.name)
};
if defs.len() != 1 {
return None;
}
defs.first().filter(|def| def.file == file && def.kind == symbol.kind)
}
/// The project-wide answer from persisted postings, overlaid by every live
/// buffer. `None` preserves the old ambiguity contract and lets the caller
/// degrade to its single-file answer.
fn indexed_references(
ws: &Workspace,
target: IndexedTarget,
include_declaration: bool,
) -> Option<Vec<Location>> {
let path = doc.path.clone()?;
let found =
vlog_refactor::find_references(&ws.sources(), &path, offset, include_declaration).ok()?;
Some(found.iter().filter_map(|(path, span)| location(ws, path, *span)).collect())
if ws.index().references_are_ambiguous(&target.def) {
return None;
}
let mut found = Vec::new();
for site in ws.index().references_to(&target.def) {
let path = ws.index().path(site.file)?;
if ws.document_for_path(path).is_none() {
found.push((path.to_path_buf(), site.name_span));
}
}
for (_, doc) in ws.open_documents() {
let Some(path) = doc.path.as_ref() else { continue };
for (id, reference) in doc.semantics.references().iter().enumerate() {
let matches = match reference.resolved().and_then(|id| doc.semantics.symbol(id)) {
Some(symbol) => indexed_def_for_symbol(ws, doc, symbol) == Some(&target.def),
None => match doc.external.get(vlog_semantic::ReferenceId(id as u32)) {
Some(ExternalTarget::Resolved(def)) => def == &target.def,
Some(ExternalTarget::Ambiguous(defs)) if defs.contains(&target.def) => {
return None;
}
_ => false,
},
};
if matches && !reference.name_span.is_empty() {
found.push((path.clone(), reference.name_span));
}
}
}
if include_declaration {
let span = ws
.document_for_path(&target.declaration_path)
.and_then(|doc| {
doc.semantics.symbols().iter().find_map(|symbol| {
(symbol.name == target.name
&& indexed_def_for_symbol(ws, doc, symbol) == Some(&target.def))
.then_some(symbol.name_span)
})
})
.unwrap_or(target.declaration_span);
found.push((target.declaration_path, span));
}
Some(locations(ws, found))
}
/// Convert all occurrences in one file with one text fetch and one line
/// index, rather than repeating both operations for every location.
fn locations(ws: &Workspace, mut found: Vec<(std::path::PathBuf, TextRange)>) -> Vec<Location> {
found.retain(|(_, span)| !span.is_empty());
found.sort_by(|(a_path, a_span), (b_path, b_span)| {
(a_path, a_span.start, a_span.end).cmp(&(b_path, b_span.start, b_span.end))
});
found.dedup();
let mut out = Vec::with_capacity(found.len());
let mut start = 0;
while start < found.len() {
let path = &found[start].0;
let end = found[start..].partition_point(|(candidate, _)| candidate == path) + start;
let Some(uri) = path_to_uri(path) else {
start = end;
continue;
};
if let Some(doc) = ws.document_for_path(path) {
let positions = doc.positions();
let mut walker = positions.walker();
out.extend(
found[start..end]
.iter()
.map(|(_, span)| Location { uri: uri.clone(), range: walker.range(*span) }),
);
} else if let Some(text) = ws.text_of(path) {
let index = LineIndex::new(&text);
let positions = Positions::new(&text, &index);
let mut walker = positions.walker();
out.extend(
found[start..end]
.iter()
.map(|(_, span)| Location { uri: uri.clone(), range: walker.range(*span) }),
);
}
start = end;
}
out
}
/// The file's own answer: what `Semantics` alone knows about this symbol.
@@ -439,6 +587,67 @@ mod tests {
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn indexed_references_equal_the_refactor_walk_they_replace() {
let (dir, ws, uri) = instantiated("xrefs_equivalence", "top.sv");
let offset = at(TOP, "sub u_b");
let indexed = references(&ws, &uri, offset, true);
let path = dir.join("top.sv");
let walked = vlog_refactor::find_references(&ws.sources(), &path, offset, true)
.expect("the existing refactor walk answers");
let walked = locations(&ws, walked);
assert_eq!(indexed, walked);
let _ = fs::remove_dir_all(&dir);
}
#[test]
#[ignore = "manual indexed-navigation latency probe"]
fn qa_indexed_references_latency_over_a_large_workspace() {
let dir = temp_dir("xrefs_latency");
let sub_path = dir.join("sub.sv");
fs::write(&sub_path, SUB).expect("write declaration");
for i in 0..4 {
fs::write(
dir.join(format!("use_{i}.sv")),
format!("module use_{i}; sub u (); endmodule\n"),
)
.expect("write use");
}
for i in 0..815 {
fs::write(
dir.join(format!("unrelated_{i}.sv")),
format!("module unrelated_{i}; logic signal_{i}; endmodule\n"),
)
.expect("write unrelated source");
}
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![dir.clone()]);
let uri = path_to_uri(&sub_path).expect("uri");
ws.set_document(uri.clone(), SUB.to_string());
assert_eq!(references(&ws, &uri, at(SUB, "sub"), true).len(), 5);
let requests = 200;
let start = std::time::Instant::now();
for _ in 0..requests {
assert_eq!(references(&ws, &uri, at(SUB, "sub"), true).len(), 5);
}
let indexed = start.elapsed();
let start = std::time::Instant::now();
let walked = vlog_refactor::find_references(&ws.sources(), &sub_path, at(SUB, "sub"), true)
.expect("old walk");
let old = start.elapsed();
assert_eq!(walked.len(), 5);
eprintln!(
"indexed references: {:.3} ms/request over 820 files; old walk: {:.3} ms/request",
indexed.as_secs_f64() * 1_000.0 / f64::from(requests),
old.as_secs_f64() * 1_000.0,
);
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn include_declaration_drops_the_declaration_and_nothing_else() {
let (dir, ws, uri) = instantiated("xrefs_nodecl", "sub.sv");
@@ -546,6 +755,35 @@ mod tests {
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn an_unsaved_open_buffer_replaces_its_saved_reference_postings() {
let (dir, mut ws, uri) = instantiated("xrefs_unsaved_uses", "top.sv");
let edited = "module top;\n\n sub only_now ();\nendmodule\n";
ws.set_document(uri.clone(), edited.to_string());
let found = references(&ws, &uri, at(edited, "sub only_now"), false);
assert_eq!(
places(&found),
vec![("other.sv".to_string(), 1), ("top.sv".to_string(), 2)],
"the new live use replaces both saved top.sv uses"
);
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn an_unsaved_declaration_move_is_reported_at_its_live_span() {
let (dir, mut ws, uri) = instantiated("xrefs_unsaved_decl", "sub.sv");
let edited = "// moved down\n\nmodule sub (input logic clk);\nendmodule\n";
ws.set_document(uri.clone(), edited.to_string());
let found = references(&ws, &uri, at(edited, "module sub") + 7, true);
assert!(
places(&found).contains(&("sub.sv".to_string(), 2)),
"the declaration comes from the live buffer, not its saved offset"
);
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn an_untitled_buffer_still_answers_from_itself() {
// No path means no place in the index and nothing to hand the engine,
+17
View File
@@ -123,6 +123,13 @@ impl Document {
Positions::new(&self.text, &self.line_index)
}
/// The source token covering `offset`, found without sweeping the buffer.
pub fn token_at(&self, offset: u32) -> Option<&Token> {
let after = self.tokens.partition_point(|token| token.span.start <= offset);
let token = self.tokens.get(after.checked_sub(1)?)?;
token.span.contains(offset).then_some(token)
}
/// Re-run only the workspace overlay, after the index was rebuilt. The
/// single-file analysis is unaffected by other files, by construction.
pub fn refresh_overlay(&mut self, index: &WorkspaceIndex) {
@@ -454,6 +461,16 @@ impl Workspace {
self.docs.get(uri)
}
/// The open document backed by `path`, if there is one.
pub fn document_for_path(&self, path: &Path) -> Option<&Document> {
self.docs.values().find(|doc| doc.path.as_deref() == Some(path))
}
/// Every open document and its URI.
pub fn open_documents(&self) -> impl Iterator<Item = (&Uri, &Document)> {
self.docs.iter()
}
/// Replace a buffer's contents and re-analyze it.
///
/// Also the one place a directory enters the folder scope: a buffer with a
+50 -2
View File
@@ -20,13 +20,13 @@ use vlog_parser::defines::{Define, DefineKind, DefineTable};
use vlog_parser::span::TextRange;
use crate::model::SymbolKind;
use crate::workspace::{Decl, DeclSite, FileFacts, SiteFact};
use crate::workspace::{Decl, DeclSite, FileFacts, ReferenceFact, SiteFact};
/// The version of the encoding below. Bump it on **any** change to what a
/// record holds or to how it is written: a store stamped with another number
/// is discarded whole, which is the only way a reader can be sure it is not
/// reading last month's field order as this month's.
pub const FACTS_FORMAT: u32 = 1;
pub const FACTS_FORMAT: u32 = 2;
impl FileFacts {
/// These facts as one line's worth of fields, tab-separated.
@@ -64,6 +64,10 @@ impl FileFacts {
out.text(base);
out.site(subclass);
}
out.tag("R", self.references.len());
for reference in &self.references {
out.reference(reference);
}
Some(out.out)
}
@@ -101,6 +105,10 @@ impl FileFacts {
for _ in 0..input.tag("S")? {
subclasses.push((input.text()?, input.site()?));
}
let mut references = Vec::new();
for _ in 0..input.tag("R")? {
references.push(input.reference()?);
}
if !input.done() {
return None;
}
@@ -111,6 +119,7 @@ impl FileFacts {
members,
instantiations,
subclasses,
references,
})
}
}
@@ -211,6 +220,27 @@ impl Writer {
self.range(define.name_span);
}
fn reference(&mut self, reference: &ReferenceFact) {
match reference {
ReferenceFact::Local { definition, occurrence } => {
self.field();
self.out.push('l');
self.range(*definition);
self.range(*occurrence);
}
ReferenceFact::External { name, paths, occurrence } => {
self.field();
self.out.push('e');
self.text(name);
self.num(paths.len() as u32);
for path in paths {
self.text(path);
}
self.range(*occurrence);
}
}
}
/// The separator before every field but the first.
fn field(&mut self) {
if self.written {
@@ -302,6 +332,24 @@ impl<'a> Reader<'a> {
name_span: self.range()?,
})
}
fn reference(&mut self) -> Option<ReferenceFact> {
match self.next()? {
"l" => {
Some(ReferenceFact::Local { definition: self.range()?, occurrence: self.range()? })
}
"e" => {
let name = self.text()?;
let count = self.num()? as usize;
let mut paths = Vec::with_capacity(count);
for _ in 0..count {
paths.push(self.text()?);
}
Some(ReferenceFact::External { name, paths, occurrence: self.range()? })
}
_ => None,
}
}
}
/// One escaped string field, back as it was written. `None` for an escape
+32 -10
View File
@@ -31,9 +31,9 @@ pub use model::{
SymbolId, SymbolKind,
};
pub use workspace::{
index_order, resolve_external, DeclSite, Def, Definition, ExternalResolutions, ExternalTarget,
FileFacts, FileId, IndexBuilder, IndexCounts, InheritanceEdge, InstantiationEdge,
WorkspaceIndex, WorkspaceSymbol,
index_order, resolve_external, DeclSite, Def, Definition, DefinitionKey, ExternalResolutions,
ExternalTarget, FileFacts, FileId, IndexBuilder, IndexCounts, InheritanceEdge,
InstantiationEdge, ReferenceSite, WorkspaceIndex, WorkspaceSymbol,
};
use std::collections::HashMap;
@@ -48,6 +48,10 @@ pub struct Semantics {
references: Vec<Reference>,
/// symbol → indices into `references`, in source order.
uses: HashMap<SymbolId, Vec<usize>>,
/// Non-empty declaration-name spans, sorted by start for cursor lookup.
symbol_positions: Vec<(TextRange, SymbolId)>,
/// Non-empty reference-name spans, sorted by start for cursor lookup.
reference_positions: Vec<(TextRange, ReferenceId)>,
}
/// Build the symbol table for one parsed file. `src` must be the text the
@@ -79,7 +83,21 @@ pub fn analyze(file: &SourceFile, src: &str) -> Semantics {
uses.entry(id).or_default().push(i);
}
}
Semantics { scopes, symbols, references, uses }
let mut symbol_positions: Vec<(TextRange, SymbolId)> = symbols
.iter()
.enumerate()
.filter(|(_, symbol)| !symbol.name_span.is_empty())
.map(|(i, symbol)| (symbol.name_span, SymbolId(i as u32)))
.collect();
symbol_positions.sort_by_key(|(span, _)| (span.start, span.end));
let mut reference_positions: Vec<(TextRange, ReferenceId)> = references
.iter()
.enumerate()
.filter(|(_, reference)| !reference.name_span.is_empty())
.map(|(i, reference)| (reference.name_span, ReferenceId(i as u32)))
.collect();
reference_positions.sort_by_key(|(span, _)| (span.start, span.end));
Semantics { scopes, symbols, references, uses, symbol_positions, reference_positions }
}
/// Point every import at the package it names, when this file declares it.
@@ -130,21 +148,18 @@ impl Semantics {
/// The declaration whose *name* covers `offset` — a cursor sitting on a
/// declared name, not anywhere in its declaration.
pub fn symbol_at(&self, offset: u32) -> Option<SymbolId> {
self.symbols.iter().position(|s| s.name_span.contains(offset)).map(|i| SymbolId(i as u32))
position_at(&self.symbol_positions, offset)
}
/// The use whose name covers `offset`.
pub fn reference_at(&self, offset: u32) -> Option<&Reference> {
self.references.iter().find(|r| r.name_span.contains(offset))
self.reference_id_at(offset).and_then(|id| self.reference(id))
}
/// The id of the use whose name covers `offset` — the key the workspace
/// index's overlay uses.
pub fn reference_id_at(&self, offset: u32) -> Option<ReferenceId> {
self.references
.iter()
.position(|r| r.name_span.contains(offset))
.map(|i| ReferenceId(i as u32))
position_at(&self.reference_positions, offset)
}
/// One use by id.
@@ -216,3 +231,10 @@ impl Semantics {
self.scopes.first().map_or(TextRange::empty(0), |s| s.span)
}
}
/// The source span covering `offset` in a non-overlapping, start-sorted table.
fn position_at<Id: Copy>(positions: &[(TextRange, Id)], offset: u32) -> Option<Id> {
let after = positions.partition_point(|(span, _)| span.start <= offset);
let (span, id) = positions.get(after.checked_sub(1)?)?;
span.contains(offset).then_some(*id)
}
+194 -7
View File
@@ -17,7 +17,7 @@ use std::collections::{BTreeMap, HashMap, HashSet};
use std::path::{Path, PathBuf};
use vlog_parser::ast::SourceFile;
use vlog_parser::defines::{collect_defines, Define, DefineTable};
use vlog_parser::defines::{collect_defines, Define, DefineKind, DefineTable};
use vlog_parser::span::TextRange;
use vlog_parser::{parse_source_tolerant, parse_tolerant, tokenize};
@@ -39,6 +39,38 @@ pub struct Def {
pub kind: SymbolKind,
}
/// Stable identity of one indexed declaration inside the current index.
///
/// A [`FileId`] may move when a file is added or removed, so this key survives
/// only as long as the [`WorkspaceIndex`] that produced it. That is exactly the
/// lifetime of every merged table in the index; callers never persist it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct DefinitionKey {
pub file: FileId,
pub name_start: u32,
pub name_end: u32,
}
impl DefinitionKey {
/// The key of an indexed definition.
pub fn of(def: &Def) -> DefinitionKey {
DefinitionKey {
file: def.file,
name_start: def.name_span.start,
name_end: def.name_span.end,
}
}
}
/// One indexed use of a declaration.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ReferenceSite {
/// The file the use is written in.
pub file: FileId,
/// Byte range of the referenced name inside that file.
pub name_span: TextRange,
}
/// One hit of [`WorkspaceIndex::workspace_symbols`].
#[derive(Debug, Clone)]
pub struct WorkspaceSymbol<'a> {
@@ -116,6 +148,14 @@ pub struct WorkspaceIndex {
/// Base class name → every class extending it, in file order then walk
/// order.
subclasses: BTreeMap<String, Vec<InheritanceEdge>>,
/// Macro name → `(file, entry-in-that-file)` for each definition.
macro_definitions: BTreeMap<String, Vec<(FileId, usize)>>,
/// Declaration → every unambiguous use, in file then source order.
reference_sites: BTreeMap<DefinitionKey, Vec<ReferenceSite>>,
/// Declarations touched by at least one ambiguous external reference.
/// Find-references refuses those rather than assigning the use to one of
/// several equally plausible declarations.
ambiguous_references: HashSet<DefinitionKey>,
}
impl WorkspaceIndex {
@@ -152,6 +192,14 @@ impl WorkspaceIndex {
self.files.get(file.0 as usize).map(PathBuf::as_path)
}
/// The id of an indexed path.
pub fn file_id(&self, path: &Path) -> Option<FileId> {
self.files
.binary_search_by(|held| held.as_path().cmp(path))
.ok()
.map(|at| FileId(at as u32))
}
/// Every file-scope declaration of `name` — module, package or typedef —
/// in disambiguation order (by file path, then by position in the file).
/// More than one means the workspace really does declare the name twice.
@@ -222,12 +270,25 @@ impl WorkspaceIndex {
/// this index models. A hover showing all of them is honest; picking one
/// silently would not be.
pub fn find_define(&self, name: &str) -> Vec<(FileId, &Define)> {
let mut out = Vec::new();
for (i, facts) in self.facts.iter().enumerate() {
let file = FileId(i as u32);
out.extend(facts.defines.all(name).into_iter().map(|d| (file, d)));
}
out
self.macro_definitions
.get(name)
.into_iter()
.flatten()
.filter_map(|&(file, entry)| {
let define = self.facts.get(file.0 as usize)?.defines.entries().get(entry)?;
Some((file, define))
})
.collect()
}
/// Every indexed use of `def`, excluding its declaration.
pub fn references_to(&self, def: &Def) -> &[ReferenceSite] {
self.reference_sites.get(&DefinitionKey::of(def)).map_or(&[], Vec::as_slice)
}
/// Whether at least one use could name `def` or another declaration equally.
pub fn references_are_ambiguous(&self, def: &Def) -> bool {
self.ambiguous_references.contains(&DefinitionKey::of(def))
}
/// Every indexed name containing `query`, case-insensitively — LSP's
@@ -373,6 +434,27 @@ impl WorkspaceIndex {
symbol.def.name_span.end
));
}
for (definition, sites) in &self.reference_sites {
for site in sites {
out.push_str(&format!(
"ref {}:{}..{} <- {}:{}..{}\n",
definition.file.0,
definition.name_start,
definition.name_end,
site.file.0,
site.name_span.start,
site.name_span.end
));
}
}
let mut ambiguous: Vec<DefinitionKey> = self.ambiguous_references.iter().copied().collect();
ambiguous.sort();
for definition in ambiguous {
out.push_str(&format!(
"ambiguous-ref {}:{}..{}\n",
definition.file.0, definition.name_start, definition.name_end
));
}
for (name, edges) in self.instantiations() {
for edge in edges {
out.push_str(&format!(
@@ -414,6 +496,7 @@ impl WorkspaceIndex {
self.members.clear();
self.instantiations.clear();
self.subclasses.clear();
self.macro_definitions.clear();
}
Some(affected) => {
for name in &affected.units {
@@ -428,6 +511,9 @@ impl WorkspaceIndex {
for name in &affected.bases {
self.subclasses.remove(name);
}
for name in &affected.macros {
self.macro_definitions.remove(name);
}
}
}
for (id, facts) in self.facts.iter().enumerate() {
@@ -468,7 +554,54 @@ impl WorkspaceIndex {
.or_default()
.push(InheritanceEdge { file, subclass: subclass.clone() });
}
for (entry, define) in facts.defines.entries().iter().enumerate() {
if define.kind != DefineKind::Define
|| affected.is_some_and(|a| !a.macros.contains(&define.name))
{
continue;
}
self.macro_definitions.entry(define.name.clone()).or_default().push((file, entry));
}
}
// A changed declaration can change how references in any file resolve,
// even when only one file's facts moved. Re-resolving compact facts is
// one in-memory pass; no source is read or parsed.
self.merge_references();
}
/// Rebuild declaration-to-occurrence postings from compact per-file facts.
fn merge_references(&mut self) {
let mut sites: BTreeMap<DefinitionKey, Vec<ReferenceSite>> = BTreeMap::new();
let mut ambiguous: HashSet<DefinitionKey> = HashSet::new();
for (id, facts) in self.facts.iter().enumerate() {
let file = FileId(id as u32);
for reference in &facts.references {
let site = ReferenceSite { file, name_span: reference.occurrence() };
match reference {
ReferenceFact::Local { definition, .. } => {
let key = DefinitionKey {
file,
name_start: definition.start,
name_end: definition.end,
};
sites.entry(key).or_default().push(site);
}
ReferenceFact::External { name, paths, .. } => {
match follow_paths(self, name, paths) {
ExternalTarget::Resolved(def) => {
sites.entry(DefinitionKey::of(&def)).or_default().push(site);
}
ExternalTarget::Ambiguous(defs) => {
ambiguous.extend(defs.iter().map(DefinitionKey::of));
}
ExternalTarget::StillUnresolved => {}
}
}
}
}
}
self.reference_sites = sites;
self.ambiguous_references = ambiguous;
}
}
@@ -484,6 +617,7 @@ struct Affected {
containers: HashSet<String>,
modules: HashSet<String>,
bases: HashSet<String>,
macros: HashSet<String>,
}
impl Affected {
@@ -498,6 +632,7 @@ impl Affected {
self.containers.extend(facts.members.iter().map(|(unit, _)| unit.clone()));
self.modules.extend(facts.instantiations.iter().map(|(module, _)| module.clone()));
self.bases.extend(facts.subclasses.iter().map(|(base, _)| base.clone()));
self.macros.extend(facts.defines.entries().iter().map(|define| define.name.clone()));
}
}
@@ -554,6 +689,27 @@ pub struct FileFacts {
/// Class declarations with a base, each under the base's name, in walk
/// order.
pub(crate) subclasses: Vec<(String, DeclSite)>,
/// Uses of declarations another file may name, stored before file ids and
/// cross-file candidates have been resolved by the finished index.
pub(crate) references: Vec<ReferenceFact>,
}
/// One reference contribution before the workspace's declarations are merged.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum ReferenceFact {
/// A use resolved to an exported declaration in this same file.
Local { definition: TextRange, occurrence: TextRange },
/// A use whose recorded paths need the workspace declaration tables.
External { name: String, paths: Vec<String>, occurrence: TextRange },
}
impl ReferenceFact {
fn occurrence(&self) -> TextRange {
match self {
ReferenceFact::Local { occurrence, .. }
| ReferenceFact::External { occurrence, .. } => *occurrence,
}
}
}
impl FileFacts {
@@ -581,6 +737,7 @@ fn facts_of(path: PathBuf, src: &str) -> FileFacts {
members: Vec::new(),
instantiations: edges_of(&tree),
subclasses: inheritance_of(&tree),
references: Vec::new(),
};
let Some(file_scope) = sem.scope(sem.file_scope()) else {
return facts;
@@ -595,6 +752,36 @@ fn facts_of(path: PathBuf, src: &str) -> FileFacts {
facts.units.push(Decl::of(unit));
collect_members(&sem, unit, &mut facts.members);
}
let exported: HashSet<(u32, u32)> = facts
.units
.iter()
.map(|decl| (decl.name_span.start, decl.name_span.end))
.chain(facts.members.iter().map(|(_, decl)| (decl.name_span.start, decl.name_span.end)))
.collect();
for reference in sem.references() {
let fact = match &reference.resolution {
Resolution::Resolved(id) => sem.symbol(*id).and_then(|symbol| {
let definition = symbol.name_span;
exported
.contains(&(definition.start, definition.end))
.then_some(ReferenceFact::Local { definition, occurrence: reference.name_span })
}),
Resolution::ExternalCandidate { paths }
| Resolution::InheritedCandidate { paths, .. }
if !paths.is_empty() =>
{
Some(ReferenceFact::External {
name: reference.name.clone(),
paths: paths.clone(),
occurrence: reference.name_span,
})
}
_ => None,
};
if let Some(fact) = fact {
facts.references.push(fact);
}
}
facts
}
+56
View File
@@ -759,6 +759,62 @@ fn an_import_that_can_supply_the_name_still_wins_over_a_same_named_unit() {
assert_eq!(defs[0].kind, SymbolKind::Typedef, "the package's typedef, not the decoy module");
}
// ----------------------------------------------------------------------
// Indexed reference postings
// ----------------------------------------------------------------------
#[test]
fn reference_postings_point_from_a_declaration_to_every_cross_file_use() {
let sources = [
("a.sv", "module top; sub u0 (); sub u1 (); endmodule\n"),
("b.sv", "module other; sub u2 (); endmodule\n"),
("sub.sv", "module sub; endmodule\n"),
];
let ws = index(&sources);
let [definition] = ws.units("sub") else { panic!("one sub declaration") };
let sites: Vec<(&Path, &str)> = ws
.references_to(definition)
.iter()
.map(|site| {
let path = ws.path(site.file).expect("site file");
let source = sources.iter().find(|(held, _)| Path::new(held) == path).unwrap().1;
(path, &source[site.name_span.as_range()])
})
.collect();
assert_eq!(
sites,
vec![(Path::new("a.sv"), "sub"), (Path::new("a.sv"), "sub"), (Path::new("b.sv"), "sub")]
);
assert!(!ws.references_are_ambiguous(definition));
}
#[test]
fn replacing_one_file_rebuilds_reference_postings_without_reparsing_the_others() {
let declaration = "module sub; endmodule\n";
let old_top = "module top; sub u0 (); sub u1 (); endmodule\n";
let new_top = "module top; sub u0 (); endmodule\n";
let mut incremental = index(&[("sub.sv", declaration), ("top.sv", old_top)]);
incremental.update_file(PathBuf::from("top.sv"), new_top);
let rebuilt = index(&[("sub.sv", declaration), ("top.sv", new_top)]);
assert_eq!(incremental.fingerprint(), rebuilt.fingerprint());
let [definition] = incremental.units("sub") else { panic!("one sub declaration") };
assert_eq!(incremental.references_to(definition).len(), 1);
}
#[test]
fn an_ambiguous_external_use_marks_every_possible_declaration() {
let ws = index(&[
("a.sv", "module dup; endmodule\n"),
("b.sv", "module dup; endmodule\n"),
("top.sv", "module top; dup u (); endmodule\n"),
]);
assert_eq!(ws.units("dup").len(), 2);
assert!(ws.units("dup").iter().all(|def| ws.references_are_ambiguous(def)));
}
// ----------------------------------------------------------------------
// Corpus acceptance
// ----------------------------------------------------------------------
+329
View File
@@ -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.
+9 -4
View File
@@ -213,6 +213,10 @@ impl WorkspaceIndex {
- `add_file` is now `add_facts(FileFacts::of(path, src))` — one implementation,
so the cached path cannot drift from the parsed one.
- Since indexed navigation (2026-08-27), the private facts also carry compact
local/external reference records used to rebuild declaration-to-occurrence
postings. That encoding change bumped `FACTS_FORMAT` from 1 to 2; no cache
migration is attempted or needed.
- `record_path` is public separately because a store keyed by path reads that
field out of every record it holds and decodes only the ones it is asked
for.
@@ -337,16 +341,17 @@ module m; sub u (); endmodule
```
```
2f0a8bd7c1d1f5a1→/w/m.sv→D→1→d→W→-→8→0→11→8→9→U→1→m→module→19→20→M→0→I→1→sub→m→19→20→12→41→22→25→S→0→9b1c04e2a7f3d081
2f0a8bd7c1d1f5a1→/w/m.sv→D→1→d→W→-→8→0→11→8→9→U→1→m→module→19→20→M→0→I→1→sub→m→19→20→12→41→22→25→S→0→R→1→e→sub→1→sub→22→25→9b1c04e2a7f3d081
```
— one define (`d` for `` `define``, name `W`, `-` for "no parameter list",
body `8`, span `0..11`, name span `8..9`), one file-scope unit (`m`, a module,
name span `19..20`), no members, one instantiation edge (of `sub`, owned by
`m` whose name is at `19..20` and whose declaration runs `12..41`, with the
site's own name span `22..25`), no subclasses, and the checksum of all of
that. The record is what lies between the hash field and the checksum; both
hashes above are illustrative.
site's own name span `22..25`), no subclasses, and one external reference fact
(`e`, name `sub`, one resolution path also named `sub`, occurrence `22..25`),
then the checksum. The record is what lies between the hash field and the
checksum; both hashes above are illustrative.
**Any change to what a record holds or how it is written bumps
`FACTS_FORMAT`** — that is the rule, written at the constant, and it is what
+36 -19
View File
@@ -28,12 +28,12 @@ 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` |
| `textDocument/documentLink` | `includes::IncludeGraph` | One link per **resolvable** `` `include``, covering the quoted path, target already resolved (`resolveProvider: false`). Search order: the including file's own directory, then each `+incdir+` of the configured filelist in order; the `<angled>` form skips the first rung. An include nothing answers to gets no link and no error. Same feature README |
| `textDocument/references` | `vlog_refactor::find_references`, else `Semantics::references_of` | Cross-file when the symbol is one the workspace index holds (a module, a package, an exported member, a port); in-file for everything else, which is what keeps a local `wire` off the workspace walk. See `docs/features/references-nav/README.md` |
| `textDocument/references` | `WorkspaceIndex::references_to`, else `Semantics::references_of` | Cross-file when the symbol is one the workspace index holds (a module, a package, an exported member, a port). Saved uses are declaration-to-occurrence postings built with the project index; open buffers overlay live semantics. No request-time project scan; returned spans are converted per touched file in one batch. See `docs/features/references-nav/README.md` |
| `textDocument/documentHighlight` | `pairs::analyze`, else `Semantics::references_of` | A scope keyword highlights its own closer; anything else highlights the symbol's occurrences in this file. Kind is always `Text`; neither answer means `null`, so the editor keeps its word highlighting. Same feature README |
| `textDocument/foldingRange` | `pairs::analyze` + comment trivia | One `Region` per matched scope pair, folded through the line *before* the closer so `end`/`endmodule` stays visible, plus one `Comment` per multi-line block comment. An unmatched opener folds nothing. Same feature README |
| `textDocument/documentSymbol` | `Semantics::document_symbols` | Hierarchical |
@@ -260,7 +260,7 @@ empty until the first `didOpen`, which is the whole saving on a large project.
**Stated plainly, because it is what a user notices:** every cross-file answer
in the table above is **scope-relative**. A definition, a `workspace/symbol`
hit, an `incomingCalls` census, a `subtypes` list, a `find_references` sweep or
hit, an `incomingCalls` census, a `subtypes` list, a references lookup or
a workspace rename covers the files in scope and no others — a symbol in a
folder the scope has not reached does not exist as far as this server is
concerned, exactly as one outside a filelist never did. Opening a file in that
@@ -461,17 +461,17 @@ spans, and `defines::{collect_defines, Define, DefineTable}`.
reference_at, references_of, document_symbols, symbol, symbols, references,
reference_id_at, scope}`, `Symbol { name, kind, name_span, decl_span, scope,
child_scope }`, `Scope::owner`, `SymbolKind`, `Resolution`, `DocumentSymbol`,
and the workspace layer — `WorkspaceIndex::{build, path, units, member,
find_define, workspace_symbols}`, `resolve_external`,
and the workspace layer — `WorkspaceIndex::{build, path, file_id, units,
member, find_define, references_to, references_are_ambiguous,
workspace_symbols}`, `resolve_external`,
`ExternalResolutions::{definition_of, get}`, `ExternalTarget::best`,
`Definition`, `Def`.
**Consumed from `vlog_refactor`:** `prepare_rename`, `rename`,
`instantiation_plan` and friends, the port refactorings, and — since
references-nav (M7) — `find_references(files, file, offset,
include_declaration) -> Result<Vec<(PathBuf, TextRange)>, String>`, which is
the cross-file half of `textDocument/references`. Every one of them takes the
same `Workspace::sources()` file set.
`instantiation_plan` and friends, and the port refactorings. Rename consumes
the `Workspace::sources()` file set. `find_references` remains available and
is the equivalence oracle for the indexed references test, but is no longer
called by the request handler.
**Consumed from `vlog_formatter`:** `format_source(&str, &Config) ->
Result<String, FormatError>` and `Config { max_width, indent_width }`.
@@ -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`.
@@ -677,11 +694,11 @@ list to `vlog_parser::KEYWORDS`. Rationale and inventory:
answering across the workspace means resolving every other file's
references *into* this one — an inverted index the workspace layer does
not build. It is a real feature, not a small addition.~~ Delivered by
**references-nav** (M7). The inverted index was never built: M2's rename
already resolves every *other* file's references and asks whether each
one lands on this declaration, so the answer came from sharing that walk
(`vlog_refactor::find_references`) rather than from new machinery. The
same round added `documentHighlight` for symbols and `foldingRange`.
**references-nav** (M7). It initially shared M2's rename walk; on
2026-08-27 `WorkspaceIndex` gained persisted declaration-to-occurrence
postings and the request moved to indexed lookup, with the old walk kept
as a correctness oracle. The same round added `documentHighlight` for
symbols and `foldingRange`.
`docs/features/references-nav/README.md`.
- [x] ~~**Not done:**~~ `lucisv.toml` discovery, `.gitignore`-aware indexing —
delivered by lucisv-core-lift (both Handshakes below marked DELIVERED).
+98 -18
View File
@@ -29,22 +29,24 @@ predicate, and three handlers.
edited but not saved, when the file is new) is answered in-file until the
next rebuild. That is the same staleness window every other cross-file
answer already has, documented in `docs/features/lucisv-server/README.md`.
- **A references answer costs what a rename costs.** The cross-file path calls
`Workspace::sources()`, which re-reads every in-scope file, and then
re-analyzes the files that spell the name. Measured at 218 ms over the
860-file corpus (below); the gate above is what keeps a local signal at
1 ms rather than paying that on every request.
- **A references answer is an indexed lookup.** Each `FileFacts` record stores
compact facts for references to externally reachable declarations. The
finished `WorkspaceIndex` resolves those facts once into declaration-to-use
postings, and a request reads only that posting list. Open documents replace
their saved postings with live `Semantics`, preserving unsaved additions and
deletions. The old `Workspace::sources()` + refactor walk remains rename's
correctness engine but is no longer on the references request path.
- **A refusal degrades to the in-file answer, it is not an error.** The shared
engine refuses an ambiguous name (declared in two indexed files) exactly as
a rename does. `textDocument/references` is a read-only convenience, so the
handler sends the file's own occurrences rather than a `RequestFailed`: a
highlight the editor can draw beats a shrug, and the refusal the user
actually needs to see is the one on the rename they then attempt.
- **Reference spans are trusted the way rename trusts them**, minus the edit
safety check: `find_references` still drops any span that does not slice
back to the name it claims, but it does not run the re-parse verification
pass, because it produces no edits and CLAUDE.md invariant #1 is about
output, not about a list of places.
- **Reference spans are produced by the semantic analysis and versioned with
the file facts.** A cache entry is content-addressed, so a saved span cannot
be paired with different bytes; an open file contributes live spans instead.
Location conversion fetches and line-indexes each touched file once, however
many occurrences it contains.
- **Read/write is not distinguished** in `documentHighlight`. LSP permits a
plain `Text` kind, and telling a read from a write in Verilog means
classifying continuous vs. procedural assignment, port direction and
@@ -56,7 +58,8 @@ predicate, and three handlers.
## Handshakes
**New public API in `vlog_refactor`** — the one handshake this round changes:
**The original public API in `vlog_refactor`**, retained for rename and as the
equivalence oracle in tests:
```rust
pub fn find_references(
@@ -72,7 +75,7 @@ current text, open buffers already overlaying disk). The result is sorted by
path then by position; an `Err` is the sentence a rename at that position
would refuse with.
**Where the sharing lives, and why there.** The collection walk is
**Where the original sharing lives.** The collection walk is
`Scope::collect_occurrences` in `crates/vlog_refactor/src/rename.rs` — lifted
out of `collect_edits`, which now calls it and turns the spans into edits.
`find_references` (`crates/vlog_refactor/src/references.rs`) calls the same
@@ -81,15 +84,24 @@ spans. The alternative considered was lifting the walk into `vlog_semantic`;
it was rejected because the walk is not a semantic query — it needs the
`Scope` cache, the workspace overlay *per file*, and the ambiguity policy,
all of which are refactor-crate concerns, and `lucisv_server` already depends
on `vlog_refactor`. Copy-pasting the walk into the server was never on the
table: a references list that disagreed with what a rename would touch is a
lie about what lucisv is going to do.
on `vlog_refactor`. The indexed implementation is compared directly with this
walk in the server tests, so moving the hot path does not create a second
semantic answer.
**Consumed from `vlog_semantic`** (all pre-existing, nothing requested):
**New public API in `vlog_semantic`:** `WorkspaceIndex::{file_id,
references_to, references_are_ambiguous}`, plus `DefinitionKey` and
`ReferenceSite`. `FileFacts`' encoded shape now includes local and unresolved
external reference facts, and `FACTS_FORMAT` is **2**. A changed file rebuilds
the merged postings from compact in-memory facts; it does not reread or parse
the other files. `Semantics::{symbol_at, reference_at, reference_id_at}` and
`Document::token_at` now use start-sorted position tables and binary search.
**Consumed from `vlog_semantic`:**
`Semantics::{reference_at, reference_id_at, references_of, symbol, symbol_at,
scope}`, `Scope::owner`, `Symbol::{name, scope, name_span}`,
`ExternalResolutions::get`, `ExternalTarget::best`,
`WorkspaceIndex::{units, member}`.
`WorkspaceIndex::{units, member, file_id, references_to,
references_are_ambiguous}`.
**Consumed from `vlog_parser`**: `token::Comment { span }` trivia and
`LineIndex::line_col` for folding.
@@ -108,11 +120,22 @@ and none was made.
## Status / TODO
- [x] **Indexed navigation performance (2026-08-27):** persist each file's
externally reachable reference facts beside its declarations, merge them
into declaration-to-occurrence postings in `WorkspaceIndex`, and route
hover/definition/references through indexed cursor and location lookups.
Preserve ambiguity refusals and unsaved open-buffer overlays; prove the
indexed answer equals the existing refactor walk before removing that
walk from the request path. Release probe: **0.064 ms/request** over 820
synthetic files and five returned locations, versus **23.431 ms** for
the old walk on the same workspace.
- [x] `Scope::collect_occurrences` factored out of `collect_edits`, with
`collect_edits` rewritten on top of it (no behaviour change; the rename
suite is the regression test).
- [x] `vlog_refactor::find_references`, new module `references.rs`, 7 tests.
- [x] `nav::references` routes through it when the symbol can leave the file.
- [x] `nav::references` routes through `WorkspaceIndex` postings when the
symbol can leave the file; the refactor walk remains its tested oracle.
- [x] `nav::leaves_this_file` — the index-only gate that keeps a local signal
off the workspace walk.
- [x] `nav::document_highlights` — symbol occurrences in this file.
@@ -142,6 +165,42 @@ and none was made.
## Work log
### 2026-08-27 — indexed navigation performance
- Began replacing the per-request `Workspace::sources()` +
`vlog_refactor::find_references` rebuild with reference facts stored in the
existing semantic index. The chosen shape is deliberately not a second
project model: `FileFacts` remains the per-file persistence and incremental
update unit, while `WorkspaceIndex` gains the merged inverted postings.
`FACTS_FORMAT` will bump because the persistent record gains fields; the
cache's version handshake therefore drops old records rather than reading a
partial shape.
- Scope remains the scope ladder's decision (filelist exactly when configured,
otherwise the folder/workspace setting already in force). This round changes
the cost of navigation inside that scope, not which files the user asked the
server to index.
- Completed the inverted index in the existing `FileFacts` /
`WorkspaceIndex` lifecycle. `FACTS_FORMAT` moved from 1 to 2, so an old cache
is discarded safely. Incremental save updates rebuild the postings from
compact facts already in memory; adding/removing files still follows the
index's path-sorted `FileId` contract.
- `nav::references` now resolves the live cursor to one indexed declaration,
reads its posting list, overlays every open buffer's current semantics, and
batches byte-span-to-LSP conversion per touched file. Duplicate declarations
and ambiguous uses still fall back to the in-file answer. Permanent tests
cover module, package-member and port references, cache round trips,
incremental equivalence, ambiguity, unsaved deletions/additions, moved live
declarations, and direct equality with `vlog_refactor::find_references`.
- Cursor hot paths no longer sweep the whole open file: semantic declaration
and reference lookup, plus macro-token hover, use binary-searched position
tables. Include definition inspects only the cursor's line.
- The ignored release latency probe builds 820 files and returns five
locations: **0.064 ms/request** averaged over 200 indexed requests; the old
source collection + refactor walk took **23.431 ms** once on the same files
(about **366×** slower). Command:
`cargo test --release -p lucisv_server
qa_indexed_references_latency_over_a_large_workspace -- --ignored --nocapture`.
### 2026-08-24 — dev agent (M7)
- **Read first**: `CLAUDE.md`, `docs/features/refactor/README.md`'s triage,
@@ -463,6 +522,27 @@ correctness or safety issue in the shipped feature.
## Review
**2026-08-27 — lead, indexed-navigation performance round (external dev:
codex).** Reviewed the full diff line-by-line and ran all three gates
independently (fmt clean, clippy silent, 1155 server tests + workspace
suite green). The design keeps the one-project-model rule: reference
facts live in `FileFacts` (the existing persistence and incremental
unit), postings are merged in `WorkspaceIndex`, and `FACTS_FORMAT` 1→2
plus the cache header's format handshake discards every v1 store whole —
verified in `index_cache.rs:324`. `macro_definitions` filters
`DefineKind::Define`, byte-identical semantics with the
`DefineTable::all` it replaces. Ambiguity is preserved everywhere it
mattered: ambiguous postings are marked, an ambiguous live overlay use
aborts to the in-file answer mid-collection, and the rename refusal
contract survives. The equivalence test pins the indexed answer to the
old `vlog_refactor::find_references` walk, which stays as rename's
engine and the oracle. Lead re-ran the ignored release probe:
0.062 ms/request over 820 files vs 21.7 ms for the old walk (~350×),
consistent with the work log's numbers. No QA-agent pass this round;
the lead review substituted, and the incremental-fingerprint,
unsaved-buffer and ambiguity tests cover the paths a QA attack would
have targeted. Accepted.
**2026-08-24 — lead.** Reviewed after QA's ship verdict (clean first
pass); gates run independently (1330 tests, 0 failures, clippy silent).
The factoring is the right move — `collect_occurrences` peeled out of
+8
View File
@@ -33,6 +33,7 @@ impl Semantics {
// the LSP queries
fn symbol_at(&self, offset: u32) -> Option<SymbolId>;
fn reference_at(&self, offset: u32) -> Option<&Reference>;
fn reference_id_at(&self, offset: u32) -> Option<ReferenceId>;
fn definition_of(&self, offset: u32) -> Option<&Symbol>;
fn references_of(&self, SymbolId) -> Vec<&Reference>;
fn document_symbols(&self) -> Vec<DocumentSymbol>;
@@ -362,6 +363,8 @@ anywhere, and under 3 % unresolved on cleanly-parsed files.
with their paths
- [x] Queries: `symbol_at`, `reference_at`, `definition_of`, `references_of`,
`document_symbols`
- [x] 2026-08-27: declaration/reference cursor queries use start-sorted
position tables and binary search rather than scanning every symbol/use
- [x] `Error` nodes are opaque; tolerant trees analyze without panicking
- [x] Tests: 19 behavior tests + 6 scanner unit tests + corpus smoke test
- [x] TODO.md §6 `vlog_semantic` checkbox
@@ -376,6 +379,11 @@ anywhere, and under 3 % unresolved on cleanly-parsed files.
## Work log
**2026-08-27 — indexed navigation.** `Semantics` now builds compact sorted
`(TextRange, SymbolId/ReferenceId)` position tables with the analysis.
`symbol_at`, `reference_at` and `reference_id_at` binary-search those tables;
their public answers and half-open span rules are unchanged.
**2026-08-26 — overlay-promotion dev agent (lead-authorized, cross-module).**
`bind.rs` gains `Target::Type`, emitted by `bind_data_type`'s unqualified arm
and nowhere else, so pass two can tell a type window from an expression.
+24 -1
View File
@@ -9,7 +9,9 @@ paths that could finish it — 19.6 % of every use on cleanly-parsed corpus file
that finishes them. `WorkspaceIndex::build` scans every file in the workspace
once and records what each one *declares* — modules, packages, file-scope
typedefs, each package's and module's exported members, and each file's
`` `define`` table. `resolve_external` walks one file's external candidates
`` `define`` table. Since 2026-08-27 it also records compact reference facts
and merges them into declaration-to-occurrence postings. `resolve_external`
walks one file's external candidates
against that index and answers them in an **overlay** keyed by reference id.
That is what turns `import prim_pkg::*` and `prim_fifo_sync u_fifo (...)` into
a jump into the file that declares them — TODO.md §6's "cross-file resolution
@@ -25,12 +27,15 @@ impl WorkspaceIndex {
fn files(&self) -> &[PathBuf]; // indexed by FileId
fn path(&self, FileId) -> Option<&Path>;
fn file_id(&self, &Path) -> Option<FileId>; // 2026-08-27
fn units(&self, name: &str) -> &[Def]; // module | package | file-scope typedef
fn member(&self, unit: &str, member: &str) -> &[Def];
fn members_of(&self, unit: &str) -> impl Iterator<Item = (&str, &[Def])>;
fn defines(&self, FileId) -> Option<&DefineTable>;
fn instantiations_of(&self, name: &str) -> &[InstantiationEdge]; // 2026-08-27
fn subclasses_of(&self, name: &str) -> &[InheritanceEdge]; // 2026-08-27
fn references_to(&self, def: &Def) -> &[ReferenceSite]; // 2026-08-27
fn references_are_ambiguous(&self, def: &Def) -> bool; // 2026-08-27
fn update_file(&mut self, PathBuf, src: &str); // 2026-08-27
fn remove_file(&mut self, &Path) -> bool; // 2026-08-27
fn fingerprint(&self) -> String; // 2026-08-27
@@ -145,6 +150,11 @@ written"). Ambiguity means something else — see below.
module stays unreachable, which is correct and is a test.
- **`` `define`` tables**: `defines::collect_defines` per file, keyed by
`FileId`, read off the same token stream the parse used.
- **Reference postings**: uses of the externally reachable declarations above.
Each file persists local declaration/use span pairs and unresolved external
candidates; after every build or incremental update, the merged declaration
tables resolve those compact facts into `DefinitionKey -> [ReferenceSite]`.
Ambiguous candidates are marked rather than assigned to a guessed target.
A declaration whose `name_span` is empty (the single-file layer's "I could not
locate this name in the source") is **not** indexed: an editor must never be
@@ -407,10 +417,23 @@ and more than half of all external candidates answered on clean files.
equal to a whole build; instantiation and inheritance edge tables
(`instantiations_of`, `subclasses_of`); `fingerprint` as the equivalence
witness
- [x] 2026-08-27 (`references-nav` performance): persisted reference facts,
declaration-to-occurrence postings, ambiguity markers and indexed macro
lookup; reference postings included in the incremental fingerprint
- [ ] Deferred (non-goals above): `` `include`` graph, elaboration
## Work log
**2026-08-27 — indexed navigation.** `FileFacts` gained compact local and
external reference records and its persisted format moved to version 2.
`WorkspaceIndex` resolves them into reverse postings after declaration tables
are merged, including on an incremental update, without rereading or reparsing
other files. The public query is `references_to`; ambiguous external uses are
tracked separately so navigation preserves the existing rename refusal. Three
focused tests cover postings, incremental/full-build equivalence, and
ambiguity, while the record round-trip and corpus acceptance cover persistence
and real-source scale.
**2026-08-26 — overlay-promotion dev agent (lead-authorized, cross-module).**
`resolve_external` gained one arm: an `InheritedCandidate`'s paths are tried
like an external candidate's, and an entry is recorded only when one lands, so
+24
View File
@@ -5,6 +5,30 @@ for you. The extension and its bundled language server share one version
number; the full engineering notes live in the
[project changelog](https://git.luci.ooo/lucio/lucisv/src/branch/master/CHANGELOG.md).
## 0.12.1 — 2026-08-27
- **Hover shows the declaration itself.** Hovering a name declared in another
file — a port at an instantiation, a module instance, a package parameter
or typedef — now shows its declaration's source line (direction, type,
width), syntax-highlighted, under the "declared in" location. Unsaved edits
in the declaring file are reflected live; very long declarations are
trimmed with a note.
## 0.12.0 — 2026-08-27
The indexed-navigation release.
- **Find All References is now a lookup, not a scan.** The index stores where
every module, package and exported member is used; a references request
reads that list and overlays your unsaved edits — around 0.06 ms on an
820-file workspace where the previous walk took 22 ms.
- **Hover, definition and references respond faster under the cursor** in
large open files: position lookups binary-search sorted tables instead of
sweeping the buffer.
- **One-time index rebuild.** The on-disk index cache format changed; the
first open after updating re-scans the workspace once (watch the progress
bar), then caching resumes as before. No setting changes.
## 0.11.0 — 2026-08-27
The large-workarea release: a project too big to scan is now a project lucisv
+19 -1
View File
@@ -30,7 +30,7 @@ Install **lucisv — Verilog/SystemVerilog** from the VS Code Extensions view,
then open a Verilog or SystemVerilog file. There is no separate server or CLI
setup.
The current release is **0.11.0**. Its platform packages include both
The current release is **0.12.1**. Its platform packages include both
`lucisv-server` and the `lucisv` command-line tool:
| Package target | Machines |
@@ -320,6 +320,24 @@ Every nesting color is a proper VS Code theme color:
}
```
## Release 0.12.1 highlights
Version 0.12.1 makes hover answer the question directly: a cross-file name
shows its declaration's own source line — `input logic [7:0] addr` for a
port, the header line for a module — not just the file and line it lives in.
## Release 0.12.0 highlights
Version 0.12.0 is the indexed-navigation release:
- Find All References reads precomputed declaration-to-use postings and
overlays your unsaved edits — ~0.06 ms on an 820-file workspace where the
previous project walk took 22 ms.
- Cursor lookups (hover, definition, references) binary-search position
tables instead of sweeping large buffers.
- The index cache format changed: the first open after updating re-scans the
workspace once, then persistent caching resumes.
## Release 0.11.0 highlights
Version 0.11.0 is the large-workarea release:
+1 -1
View File
@@ -2,7 +2,7 @@
"name": "lucisv",
"displayName": "lucisv — Verilog/SystemVerilog",
"description": "Fast Verilog/SystemVerilog formatting, linting, navigation, refactoring, semantic highlighting and RTL design intelligence.",
"version": "0.11.0",
"version": "0.12.1",
"publisher": "guoliangchen",
"author": "Guoliang Chen",
"license": "MIT",