Files
lucisv/docs/features/references-nav/README.md
T

28 KiB
Raw Blame History

references-nav

M7 of the refactoring plan (docs/features/refactor/README.md), the first milestone taken from that plan's "LSP-parity and plumbing gaps" triage.

Goal

Three navigation capabilities that were all wiring over machinery the tree already had. Cross-file find-all-references: textDocument/references answered in-file only, while M2's rename had been collecting cross-file reference sets since it shipped — so lucisv could change references it could not list. Document highlight for symbols: the cursor on a signal now highlights its declaration and every use in the file, where before only a begin/end pair answered and everything else fell through to the editor's word matching. Folding ranges: pairs.rs already matches every begin/end-family pair for the rainbow, and textDocument/foldingRange is that same data on a standard capability. No new analysis was written for any of the three; the whole milestone is one shared collection function, one predicate, and three handlers.

Assumptions

  • The workspace index is the authority on what can be named from another file. nav::leaves_this_file decides whether a references request walks the workspace by asking WorkspaceIndex::units / ::member about the name under the cursor — not by re-deriving is_unit/is_exported, which are private to vlog_semantic and would be language knowledge in the protocol layer. Consequence: a declaration the index has not seen yet (a buffer 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 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.
  • 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 inout — an analysis worth building for a lint rule, not for a highlight colour.
  • Folding is line-based. No startCharacter/endCharacter: editors default to whole-line folding, and a character-precise range for begin/end would buy nothing a reader can see.

Handshakes

New public API in vlog_refactor — the one handshake this round changes:

pub fn find_references(
    files: &[(PathBuf, String)],
    file: &Path,
    offset: u32,
    include_declaration: bool,
) -> Result<Vec<(PathBuf, TextRange)>, String>

files is the same in-scope set rename/prepare_rename take (path and 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 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 Scope::build → locate → collect_occurrences sequence and keeps the 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.

Consumed from vlog_semantic (all pre-existing, nothing requested): 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}.

Consumed from vlog_parser: token::Comment { span } trivia and LineIndex::line_col for folding.

Consumed from this crate's own pairs.rs: analyze(&[Token]) -> ScopeAnalysis, unchanged. folding.rs is its fourth consumer (documentHighlight, the missing-closer warnings, lucisv/scopePairs, folding) and reads only pairs, never unmatched_open/unmatched_close.

Promised to the editors: nothing new to configure. foldingRange is a standard capability both VS Code's built-in client and Neovim's vim.lsp consume on their own once it is advertised; no extension change was needed and none was made.

Requested of other modules: none.

Status / TODO

  • 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).
  • vlog_refactor::find_references, new module references.rs, 7 tests.
  • nav::references routes through it when the symbol can leave the file.
  • nav::leaves_this_file — the index-only gate that keeps a local signal off the workspace walk.
  • nav::document_highlights — symbol occurrences in this file.
  • server.rs: documentHighlight tries the scope pair first, the symbol second, and still declines both with null.
  • folding.rs — one range per matched pair, plus multi-line block comments, 15 tests.
  • foldingRangeProvider advertised in main.rs.
  • e2e: one session covering cross-file references (both includeDeclaration values), foldingRange and documentHighlight.
  • docs/features/lucisv-server/README.md: capability table, the "not done" list, and Handshakes updated.
  • Not done, deliberately: line-comment run folding (// blocks). The token stream carries each // comment separately, so folding a run of them means deciding what counts as one run (blank lines? indentation changes? a comment after code on its line?). That is a judgement call with no obviously right answer, and the brief said skip it if it is not trivial. Block comments, which have their own delimiters, are done.
  • Not done, deliberately: a references answer for an ambiguous name. It falls back to the file's own occurrences; returning both declarations' reference sets, the way definition returns both locations, is a real option and a separate decision.
  • TODO.md and the refactor umbrella checklist were not touched, per the milestone brief — the lead owns the two backlog checkboxes this closes ("Cross-file find-all-references", "Folding ranges", "Document highlight" in docs/features/refactor/README.md).

Work log

2026-08-24 — dev agent (M7)

  • Read first: CLAUDE.md, docs/features/refactor/README.md's triage, docs/features/lucisv-server/README.md in full, then nav.rs, pairs.rs, state.rs, server.rs, main.rs, vlog_refactor/src/rename.rs and vlog_semantic's workspace.rs/model.rs. The design decisions below all came out of that reading rather than out of the brief.
  • The sharing shape. collect_edits was two things in one function: the walk that finds every occurrence, and the conversion of spans into checked edits. Splitting it at that seam gave collect_occurrences with no new logic and no change to the rename's behaviour — the ambiguity refusal, the text.contains(&name) prefilter and the on-demand analysis cache all stayed exactly where they were. find_references is 30 lines on top of it. vlog_semantic was left alone; the reasoning is in Handshakes.
  • The gate was the interesting part, not the collection. A naive wiring would call find_references for every references request, which re-reads the workspace to answer "where else is this wire" — 218 ms instead of 1 ms, on every request, for the commonest case. The predicate asks the index whether the name is reachable from outside (units, or member under the unit that owns the declaring scope), which needs no file I/O and no duplicated visibility rules. It falls out of that construction that a module's ports are cross-file referenceable — the index exports exactly what a connection list can name — so .clk(...) connections in other files now show up as references to the port, which is right and is tested.
  • documentHighlight gained a second answer rather than a second handler. pairs::highlights is tried first and nav::document_highlights second; both return Option, and both None means null, which is what keeps the editor's own word highlighting alive where lucisv knows nothing. The two never compete: a scope keyword is never an identifier.
  • Folding stops one line short of the closer (endLine = close line - 1). LSP hides startLine + 1 ..= endLine, so this leaves end/endmodule on screen — the convention that lets a reader see what was collapsed. Block comments do the opposite and fold through their last line, because a */ alone on screen tells nobody anything. A pair that opens and closes with nothing between the two lines produces no range at all.
  • An unmatched opener produces no fold, for free: analyze puts it on unmatched_open, not on pairs. This is the failure mode that makes people switch folding off — a missing end folding the rest of the file away — and it is pinned by its own test rather than left to the data structure.
  • Trailing trivia was nearly missed. The first draft of folding.rs walked token.leading only, which silently drops every comment written after code on its own line. Caught by writing the test before believing the code; both halves are now iterated and both have a test.
  • Perf, measured on the corpus (release binary, real stdio session, best of three, initialize + didOpen + one request + shutdown): references on prim_lfsr (declared once, instantiated in 4 other files, 820 source files indexed) — 218 ms for the request, 535 ms for the whole session against a 317 ms session baseline. references on a local logic in the same file — 1 ms, i.e. the gate is shut and no walk happens. Well inside the 1 s budget the brief set.
  • No new dependencies. No unsafe, no unwrap/expect/panic! outside #[cfg(test)], no new #[allow].
  • Did not touch vlog_parser, vlog_formatter, vlog_linter, lucisv_core, crates/lucisv, editors/, TODO.md or the umbrella plan. Did not run git commit/git push. No version bump (0.5.0 is M14's).

Results. cargo fmt --all -- --check: clean. cargo clippy --all-targets: 0 warnings. cargo test --workspace: 1329 passed, 0 failed, of which 34 are new: 15 in folding.rs, 11 added to nav.rs (20 there in total), 7 in references.rs, and 1 e2e (18 in that file now). node editors/vscode/smoke.js target/release/lucisv-server: OK. Files added: crates/vlog_refactor/src/references.rs, crates/lucisv_server/src/folding.rs, this README. Files edited: crates/vlog_refactor/src/{lib.rs,rename.rs}, crates/lucisv_server/src/{main.rs,server.rs,nav.rs}, crates/lucisv_server/tests/e2e.rs, docs/features/lucisv-server/README.md.

QA log

2026-08-24 — QA agent

Gates

  • cargo fmt --all -- --check — clean.
  • cargo clippy --all-targets — clean, zero warnings (forced re-check after touching every changed/new file, not a cache hit).
  • cargo test --workspace — 1329 passed, 0 failed, matching the Work log's count exactly, before I added one regression test (see below); 1330 after.
  • node editors/vscode/smoke.js target/release/lucisv-server — OK.
  • cargo test -p vlog_refactor standalone — 48/48 rename behavior tests green (tests/rename.rs), confirming the collect_edits/ collect_occurrences split changed nothing rename depends on.

All gates: pass, claims confirmed.

The factoring (collect_occurrences out of collect_edits)

Read the diff of crates/vlog_refactor/src/rename.rs line by line rather than trusting the green suite alone. collect_occurrences is exactly the old collect_edits walk with edits_from_spans peeled off the end; collect_edits now calls it and applies edits_from_spans to every (file, spans) pair, filtering empty results exactly as before (if !edits.is_empty()). No reordering, no new dedup, no change to the ambiguity refusal or the substring prefilter. find_references shares the same (usize, Vec<TextRange>) shape and does its own sort/dedup/declaration handling on top — it does not lean on any rename-specific step. Verdict: behavior-identical, confirmed both by the diff and by 48/48 green.

Attempts to break it (vlog_refactor::find_references, API level)

Wrote a scratch test file (crates/vlog_refactor/tests/qa_probe_refs.rs, removed after the round, not committed) exercising the public API directly:

  • bind: bind top leaf b_leaf (); correctly appears as a reference to leaf alongside the declaration.
  • Instance arrays (sub u[3:0] ();): found, alongside the declaration.
  • Ambiguous declaration (two files declare dup): find_references returns the same refusal sentence a rename at that position would (`dup` is declared in more than one indexed file...) — verbatim reuse of the rename refusal message, as the Handshakes section promises.
  • import p::* glob in a third file: the package member is found at the glob-import site in a file that is neither the declaring file nor the file the cursor started in.
  • End labels: begin : blk ... end : blk, asking for references to blk, returns 2 occurrences (the begin label and the end label) — end labels do appear in a references answer. Assessed, not a bug: M2 already made end labels references of their declaration (docs/features/refactor-rename/README.md), and since references and rename share one walk, hiding them from references while a rename edits them would be exactly the "two answers about one symbol" lie the Handshakes section says this feature refuses to tell. Correct as built.
  • Rename ↔ references consistency: for a cross-file port case (module sub with port clk, instantiated by name in two other files), the set of (file, start-offset) pairs from rename's edits and from find_references(..., include_declaration: true) are identical after sorting. Spot-checked in code, not just eyeballed.

Attempts to break it (lucisv_server::nav, handler level)

Six scratch tests added temporarily to nav.rs's own test module, run, then removed (git diff --stat on nav.rs returned to the dev's exact 344/-20 shape before I added the one permanent test below):

  • Ambiguous name degrades to in-file, not error, not empty. Two files declare dup; leaves_this_file correctly says "yes, ask the workspace" (the index holds dup as a unit), find_references refuses it as ambiguous, and references() falls back to exactly one location — the in-file declaration. This is the claim in Assumptions ("a refusal degrades to the in-file answer, it is not an error") and it holds. This had no dedicated regression test among the 34 new ones (the only ambiguity test in nav.rs, an_ambiguous_workspace_name_returns_every_location, is for definition, not references) — see "Fix applied" below.
  • Cursor on a comment, or a keyword. document_highlights returns None (not an empty list); references returns an empty Vec (not an error) — both correct, both matching the null-not-error contract the README states.
  • Sibling scope, same signal name (n declared inside begin : b1 and independently inside a sibling begin : b2): document_highlights on b1's n returns exactly b1's declaration and use, never touching b2's unrelated n. Correct isolation.
  • Unsaved buffer overlay, two shapes. (1) A file already known to the index (sub.sv, module sub already indexed at open_roots time) gets an unsaved didChange-style edit to top.sv adding a new instantiation of sub. references on sub does see the new instantiation — Workspace::sources() picks up the live buffer text even though the index has not rebuilt. (2) A brand-new file (sub.sv, never written to disk, never scanned by open_roots) is opened as a pure buffer, while an on-disk top.sv genuinely instantiates it. references on sub sees only the in-file declaration — the gate (WorkspaceIndex, save- triggered) has never heard of sub as a unit, so leaves_this_file stays shut, and top.sv's real instantiation is invisible until a save rebuilds the index. Both outcomes match the documented staleness window exactly (Assumptions: "a declaration the index has not seen yet ... is answered in-file until the next rebuild").
  • Port referenceable from both sides, on the real binary (see below).

Fix applied (small, unambiguous per CLAUDE.md's QA license): added a_name_declared_in_two_files_degrades_references_to_the_in_file_answer to crates/lucisv_server/src/nav.rs (permanent, not a probe) — the one claim above that had behavior verified correct but zero regression coverage. Workspace test count is now 1330 (was 1329), gates re-run green after the addition.

documentHighlight, on the real binary

Independent stdio session (own script, not tests/e2e.rs) against a 2-file fixture (leaf.sv/top.sv, port clk_i, an always_ff block):

  • Cursor on clk_i inside the sensitivity list → highlights the port declaration (line 1) and this in-file use (line 5), kind: Text (1).
  • Cursor on the begin keyword → pairs::highlights answers first: begin and its matching end, not the symbol path. Fallthrough order confirmed live, not just read from the diff.
  • Cursor on the always_ff keyword → null.

Folding, independent attacks

Six scratch tests added temporarily to folding.rs's own test module (run, then removed — file back to its original 249 lines):

  • A 2-line begin/end (initial begin\nend): produces no range — through = close_line - 1 == open_line, so push drops it. Only the enclosing module folds. Matches the documented "opens and closes with nothing between the two lines produces no range at all."
  • CRLF file, module + initial begin/end + a 2-line block comment, all with \r\n line endings: every fold lands on the right line, no off-by-one from the \r bytes.
  • An unmatched opener sitting between two matched pairs (begin (unmatched) between a matched begin/end before it and another matched begin/end after it, all inside one module): the unmatched begin produces no fold, the two real pairs fold correctly, and — significant — the later begin matches its own end rather than the earlier, orphaned one picking it up. Confirms the pair-matcher is a proper LIFO stack per keyword family, not a naive first-open/first-close scan, so an interior unmatched opener cannot cause a later, unrelated pair to be misattributed. No fold reached past the file's own last line either.
  • The "unmatched-begin file from the rainbow QA" round itself does not exist as a checked-in fixture (searched the tree; no rainbow feature README, no saved fixture file) — reconstructed the shape described in the M7 QA brief (an opener with no closer, amid otherwise-valid code) rather than reusing a file that isn't in this tree.
  • One-line block comment already covered by the dev's own a_one_line_comment_of_either_spelling_folds_nothing — read and confirmed correct rather than re-proven.

Independent e2e: cross-file references + folding round trip

Own hand-rolled Python stdio client (write-then-read-all, same rationale tests/e2e.rs documents at its own top, not the dev's script or fixture) — leaf.sv (a clocked module) instantiated twice by top.sv:

  • references on leaf's declaration, includeDeclaration: true → 3 hits (declaration + both instantiations); false → 2 hits, declaration correctly dropped and nothing else lost.
  • references on the connection-side .clk_i(...) name in top.sv (not the declaration, not the expression) → resolves to the port's full reference set: the port declaration, its in-file use inside the always_ff sensitivity list, and both connection sites across the two instantiations. Confirms ports are reachable from a connection, not only from the declaration side (the corpus perf run below confirms the declaration-side direction).
  • foldingRange on leaf.sv → exactly two ranges, the module (0–8) and the always_ff block (5–7), both boundaries correct.

Performance

Reconfirmed the dev's corpus measurement independently (own Python driver, release binary, real stdio session, initialize → didOpen → one references request → shutdown): references on prim_lfsr's module name — 528.5 ms whole-session wall time. A 3-run baseline session with no request (initialize/initialized/shutdown/exit only) measured ~317 ms, so the request itself costs ~211 ms — matches the Work log's 218 ms / 535 ms / 317 ms triad closely enough to call it the same number, measured twice.

New measurement: a common name, the text-prefilter's worst case. Ports named clk_i appear (as a substring) in 360 of 860 corpus files — every one of those pays the "does the text contain the name" check and, on a hit, a full re-analysis. references on prim_lfsr's own clk_i port — 3–4 runs, 612–627 ms whole-session, i.e. ~295–310 ms for the request alone. That is only ~1.4× the already-cross-file prim_lfsr case above, not a blowup, even though the prefilter had roughly 8× more files to look past (45 files spelling prim_lfsr vs. an estimated few hundred spelling clk_i, not counted exactly). Comfortably inside any reasonable request budget. This scenario was not in the dev's own perf writeup — worth having on record since "a port named like every other port in the codebase" is a completely ordinary real-world query, not an edge case.

Corpus file count, a documentation-only discrepancy. The Work log says "820 source files indexed"; the Assumptions section separately says "the 860-file corpus". A plain find over corpus/ for .v/.sv/.svh/.vh returns exactly 860, matching every earlier round's number for this same directory (docs/features/lucisv-server/README.md's QA log, 2026-08-19: "860 files"). corpus/ itself is listed in the repo's own .gitignore, but the LSP root was pointed at corpus/, so that rule is moot; however corpus/ contains 19 nested .gitignore files from the vendored upstream repos themselves (corpus/ibex/.gitignore, corpus/opentitan/.gitignore, etc.), and the workspace walk has honored .gitignore unconditionally since lucisv-core-lift landed the same day as this round. So 820 vs. 860 is plausibly real — some vendored generated/build files are legitimately excluded now that they weren't when the 860 number was first measured — but I could not independently confirm 820 exactly: LSP exposes no "how many files did you index" answer, and workspace/symbol is capped at 256. Not filed as a defect — the explanation is plausible and the actual measured behavior (references answers, timings) was correct throughout — but flagging the inconsistency between the README's own two numbers (820 in Work log vs. 860 in Assumptions, for what reads as the same measurement) so whoever owns the prose can pick one and true it up.

A process discrepancy worth the lead's attention (not a code defect)

The Work log states plainly: "Did not touch ... TODO.md or the umbrella plan." But git diff HEAD -- TODO.md currently shows an uncommitted, 20-line addition — the M7–M14 checklist items — that is not part of HEAD (6036a62, which only touched docs/features/refactor/README.md per git show --stat). I did not revert it (TODO.md is explicitly out of QA's scope per the round brief, and I cannot tell from the working tree alone whether this is unfinished, not-yet- committed lead work from the same triage session, or something the dev agent added despite its own claim). Flagging so the lead can reconcile the Work log's claim against what is actually sitting in the working tree before commit.

Summary

Claim Verdict
Gates (fmt/clippy/test/smoke) Pass, 1329 confirmed (1330 after my one added test)
collect_occurrences factoring is behavior-identical Pass — diff-reviewed and 48/48 rename tests green
find_references: bind, instance arrays, glob import, ambiguous refusal, end labels, rename/references consistency Pass, all as documented
nav::leaves_this_file gate, ambiguous degrade, sibling isolation, comment/keyword null, unsaved-overlay behavior (both shapes), staleness window Pass, all as documented
Ports cross-file referenceable from both the declaration and a connection Pass, confirmed on the real binary
documentHighlight fallthrough order (pairs first, symbol second, null third) Pass, confirmed on the real binary
Folding: 2-line block, CRLF, unmatched-opener-amid-matched-pairs (LIFO correctness) Pass
Independent e2e round trip (references × 2 + folding) Pass
Perf: prim_lfsr corpus measurement Pass, reconfirmed independently (~211 ms request, matches dev's 218 ms)
Perf: common-name worst case (new measurement) Pass — ~300 ms request, no blowup
Corpus file count in the README (820 vs. 860) Informational — plausible, not independently confirmable, prose-only inconsistency
TODO.md untouched (Work log claim) Contradicted by the working tree — flagged for the lead, not fixed

No corruption, no crash, no silent wrong answer found anywhere. One permanent test added (small, unambiguous, per CLAUDE.md). No probe files left in the tree; nav.rs and folding.rs diffs verified to match the dev's original shape plus exactly my one addition.

Verdict: ship, with the two informational items (corpus count prose, TODO.md discrepancy) left for the lead to reconcile — neither is a correctness or safety issue in the shipped feature.

Review

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 rename with the edit-conversion left behind, QA line-verified it behavior-identical — and leaves_this_file asking the index instead of re-deriving exportedness is exactly the no-second-resolution rule the umbrella plan demands. Folding as the fourth consumer of pairs::analyze cost one file. QA's added regression test for the ambiguous-degrade path is accepted with thanks; its corpus-count discrepancy note (820 vs 860) is the gitignore-aware walk, as suspected, and its TODO.md flag was the lead's own uncommitted M7–M14 queue. Rename↔references span consistency was verified — the property that makes this milestone honest. Accepted; M7 checked off in the umbrella plan and TODO.md §8.