From 3c55783e0956890b123c93c4cf19e75e5ba7a88e Mon Sep 17 00:00:00 2001 From: Guoliang Chen Date: Mon, 24 Aug 2026 22:53:38 -0700 Subject: [PATCH] References-nav M7: cross-file references, folding, document highlight MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit textDocument/references now answers across files by reusing rename's occurrence walk (collect_occurrences factored out of collect_edits, behavior-identical) — a module, port or package member lists every use the index scope can see; the cross-file gate asks the workspace index, never re-derives exportedness, and an ambiguous name degrades to the in-file answer. foldingRange is the fourth consumer of pairs::analyze (end line stays visible, unmatched openers fold nothing, block comments included); documentHighlight lights a symbol's in-file occurrences with the begin/end pair highlighting preserved. M7-M14 queue added to TODO §8. Co-Authored-By: Claude Fable 5 --- TODO.md | 20 ++ crates/vfmt_server/src/folding.rs | 249 +++++++++++++ crates/vfmt_server/src/main.rs | 20 +- crates/vfmt_server/src/nav.rs | 393 ++++++++++++++++++-- crates/vfmt_server/src/server.rs | 34 +- crates/vfmt_server/tests/e2e.rs | 111 ++++++ crates/vlog_refactor/src/lib.rs | 10 +- crates/vlog_refactor/src/references.rs | 182 ++++++++++ crates/vlog_refactor/src/rename.rs | 41 ++- docs/features/refactor/README.md | 7 +- docs/features/references-nav/README.md | 478 +++++++++++++++++++++++++ docs/features/vfmt-server/README.md | 38 +- 12 files changed, 1521 insertions(+), 62 deletions(-) create mode 100644 crates/vfmt_server/src/folding.rs create mode 100644 crates/vlog_refactor/src/references.rs create mode 100644 docs/features/references-nav/README.md diff --git a/TODO.md b/TODO.md index e4ae61f..5a84a86 100644 --- a/TODO.md +++ b/TODO.md @@ -596,5 +596,25 @@ section only tracks the milestones. - [x] **M6 `completion-templates`** — context-gated statement/item snippet completion from the server (if/else, case, always, loops, declarations), reconciled with the static VS Code snippets; version 0.4.0. +- [x] **M7 `references-nav`** — cross-file find-all-references (reuse + M2's collection machinery), document highlight, folding ranges from the + rainbow's pair data. +- [ ] **M8 `inlay-hints`** — port-name hints on ordered connections and + parameter-name hints on ordered `#(...)` overrides, from the index. +- [ ] **M9 `file-watching`** — `workspace/didChangeWatchedFiles` for + sources and the filelist; reindex on external changes (git pull, + filelist edits outside the editor). +- [ ] **M10 `include-nav`** — clickable `` `include`` lines resolved + through the filelist's `+incdir+`s; cross-file `` `define`` lookup + along the include graph. +- [ ] **M11 `hierarchy`** — module hierarchy both directions (who + instantiates X / what X instantiates) over LSP callHierarchy. +- [ ] **M12 `semantic-lints`** — unused-signal, undriven-net, + multiply-driven: the first semantic lint rules on `vlog_semantic`. +- [ ] **M13 `cli-filelist`** — `vfmt -f files.f` on the command line, + reusing M1's parser; format/lint exactly the project's files. +- [ ] **M14 `macro-expansion`** — single-step macro expansion on hover + (the define-table README's promised follow-up); version 0.5.0 with a + CHANGELOG entry covering M7–M14. - [ ] Backlog (extract module, inline, `.*` expansion, ANSI conversion, organize imports, …) — triaged in the umbrella README after M5. diff --git a/crates/vfmt_server/src/folding.rs b/crates/vfmt_server/src/folding.rs new file mode 100644 index 0000000..2872039 --- /dev/null +++ b/crates/vfmt_server/src/folding.rs @@ -0,0 +1,249 @@ +//! `textDocument/foldingRange`. +//! +//! No new analysis: a foldable region is a matched scope pair, which +//! `pairs::analyze` already computes for the rainbow and the missing-closer +//! warnings, or a block comment, which the lexer already attached as trivia. +//! This module is the fourth consumer of the first and the second of the +//! second. See `docs/features/references-nav/README.md`. + +use lsp_types::{FoldingRange, FoldingRangeKind}; +use vlog_parser::token::Comment; +use vlog_parser::TextRange; + +use crate::pairs::analyze; +use crate::state::Document; + +/// Every foldable region in a buffer: one per matched scope pair, plus every +/// block comment that spans more than one line. +/// +/// A keyword whose counterpart never arrived is **not** foldable — `analyze` +/// leaves it out of `pairs`, and folding to the end of the file because an +/// `end` is missing is exactly the behaviour that makes users turn folding +/// off. Nothing is capped: a fold list is one range per block, and an editor +/// that asked for it wants all of them. +pub fn folding_ranges(doc: &Document) -> Vec { + let mut out: Vec = Vec::new(); + for pair in analyze(&doc.tokens).pairs { + // The closing keyword's own line stays visible: LSP hides + // `startLine + 1 ..= endLine`, so folding through the line *before* + // the closer leaves `end`/`endmodule` on screen, which is how a + // reader keeps track of what was collapsed. + let through = line(doc, pair.close.start).saturating_sub(1); + push(&mut out, line(doc, pair.open.start), through, FoldingRangeKind::Region); + } + for comment in comments(doc) { + // A comment has no closing construct worth keeping on screen, so the + // whole of it folds into its first line — what an editor does for + // `/* */` in every other language. + let through = line(doc, last_byte(comment.span)); + push(&mut out, line(doc, comment.span.start), through, FoldingRangeKind::Comment); + } + out.sort_by_key(|range| (range.start_line, range.end_line)); + out.dedup_by(|a, b| a.start_line == b.start_line && a.end_line == b.end_line); + out +} + +/// Add one range, unless there is nothing between its two lines to hide. +fn push(out: &mut Vec, start_line: u32, end_line: u32, kind: FoldingRangeKind) { + if end_line <= start_line { + return; + } + out.push(FoldingRange { start_line, end_line, kind: Some(kind), ..Default::default() }); +} + +/// Every comment the lexer attached to this buffer's tokens, in no particular +/// order — trivia hangs off the token that follows it, or, for a trailing +/// comment, the one it follows. +fn comments(doc: &Document) -> impl Iterator { + doc.tokens.iter().flat_map(|token| token.leading.iter().chain(token.trailing.iter())) +} + +/// The 0-based line a byte offset falls on. `LineIndex` counts from 1; LSP +/// counts from 0. +fn line(doc: &Document, offset: u32) -> u32 { + doc.line_index.line_col(offset).0.saturating_sub(1) +} + +/// The last byte of a span, so a comment's end line is the line its `*/` sits +/// on rather than whatever follows it. +fn last_byte(span: TextRange) -> u32 { + span.end.saturating_sub(1).max(span.start) +} + +#[cfg(test)] +mod tests { + use super::*; + use vlog_semantic::WorkspaceIndex; + + fn doc_of(text: &str) -> Document { + Document::new(None, text.to_string(), &WorkspaceIndex::default()) + } + + /// Every fold as `(start line, end line, kind)`, kinds spelled short. + fn folds(text: &str) -> Vec<(u32, u32, &'static str)> { + folding_ranges(&doc_of(text)) + .into_iter() + .map(|range| { + let kind = match range.kind { + Some(FoldingRangeKind::Comment) => "comment", + Some(FoldingRangeKind::Region) => "region", + other => panic!("unexpected kind {other:?}"), + }; + (range.start_line, range.end_line, kind) + }) + .collect() + } + + #[test] + fn a_module_folds_from_its_header_to_the_line_before_endmodule() { + // The `endmodule` line itself stays visible, which is the whole point + // of stopping one line short of the closer. + let text = "module m;\n wire a;\n wire b;\nendmodule\n"; + assert_eq!(folds(text), vec![(0, 2, "region")]); + } + + #[test] + fn nested_begins_each_get_their_own_range() { + let text = concat!( + "module m;\n", // 0 + " initial begin\n", // 1 + " if (x) begin\n", // 2 + " y = 1;\n", // 3 + " end\n", // 4 + " end\n", // 5 + "endmodule\n", // 6 + ); + assert_eq!( + folds(text), + vec![(0, 5, "region"), (1, 4, "region"), (2, 3, "region")], + "module, outer begin, inner begin" + ); + } + + #[test] + fn a_generate_block_folds_like_any_other_scope() { + let text = concat!( + "module m;\n", // 0 + " generate\n", // 1 + " if (A) begin : g\n", // 2 + " wire a;\n", // 3 + " end\n", // 4 + " endgenerate\n", // 5 + "endmodule\n", // 6 + ); + assert_eq!(folds(text), vec![(0, 5, "region"), (1, 4, "region"), (2, 3, "region")]); + } + + #[test] + fn a_function_and_a_case_fold_too() { + let text = concat!( + "module m;\n", // 0 + " function int f;\n", // 1 + " case (x)\n", // 2 + " 1: f = 1;\n", // 3 + " endcase\n", // 4 + " endfunction\n", // 5 + "endmodule\n", // 6 + ); + assert_eq!(folds(text), vec![(0, 5, "region"), (1, 4, "region"), (2, 3, "region")]); + } + + #[test] + fn a_scope_that_opens_and_closes_on_one_line_folds_nothing() { + // `end_line <= start_line` means there is no hidden line to gain. + let text = "module m;\n initial begin x = 1; end\nendmodule\n"; + assert_eq!(folds(text), vec![(0, 1, "region")], "the module only"); + } + + #[test] + fn an_opener_that_never_closes_produces_no_range() { + // The failure this guards: folding an unclosed `begin` through the end + // of the file, which hides code the user is in the middle of writing. + let text = "module m;\n initial begin\n x = 1;\nendmodule\n"; + assert_eq!(folds(text), vec![(0, 2, "region")], "the module matched; the begin did not"); + } + + #[test] + fn a_stray_closer_produces_no_range_either() { + // The `begin` that *did* close has nothing between its two lines, so + // the module is the only fold and the stray `end` adds none. + let text = "module m;\n initial begin\n end\n end\nendmodule\n"; + assert_eq!(folds(text), vec![(0, 3, "region")]); + } + + #[test] + fn a_multi_line_block_comment_folds_as_a_comment() { + let text = concat!( + "/* the header\n", // 0 + " two lines */\n", // 1 + "module m;\n", // 2 + " wire a;\n", // 3 + "endmodule\n", // 4 + ); + assert_eq!(folds(text), vec![(0, 1, "comment"), (2, 3, "region")]); + } + + #[test] + fn a_one_line_comment_of_either_spelling_folds_nothing() { + let text = "// a line\n/* one line */\nmodule m;\n wire a;\nendmodule\n"; + assert_eq!(folds(text), vec![(2, 3, "region")], "only the module"); + } + + #[test] + fn a_trailing_block_comment_is_reached_too() { + // Trivia hangs off the following token — except a trailing comment, + // which hangs off the preceding one. Missing that half would silently + // drop every comment written after code on its line. + let text = "module m;\n wire a; /* why\n this net exists */\nendmodule\n"; + assert!(folds(text).contains(&(1, 2, "comment")), "got {:?}", folds(text)); + } + + #[test] + fn a_comment_at_the_end_of_the_file_is_reached_through_the_eof_token() { + let text = "module m;\nendmodule\n/* a tail\n comment */\n"; + assert!(folds(text).contains(&(2, 3, "comment")), "got {:?}", folds(text)); + } + + #[test] + fn an_empty_file_folds_nothing() { + assert!(folds("").is_empty()); + assert!(folds("\n\n\n").is_empty()); + } + + #[test] + fn a_file_that_does_not_lex_folds_nothing() { + // `Document::new` leaves `tokens` empty, so there is neither a pair + // nor a comment to report — not a truncated stream to guess from. + let doc = doc_of("module m;\n wire a; /* unterminated\n"); + assert!(doc.tokens.is_empty()); + assert!(folding_ranges(&doc).is_empty()); + } + + #[test] + fn the_ranges_come_back_sorted_and_without_duplicates() { + let text = concat!( + "module m;\n", // 0 + " initial begin\n", // 1 + " x = 1;\n", // 2 + " end\n", // 3 + " initial begin\n", // 4 + " y = 1;\n", // 5 + " end\n", // 6 + "endmodule\n", // 7 + ); + let ranges = folds(text); + assert_eq!(ranges, vec![(0, 6, "region"), (1, 2, "region"), (4, 5, "region")]); + let mut sorted = ranges.clone(); + sorted.sort(); + assert_eq!(ranges, sorted, "an editor reads them in order"); + } + + #[test] + fn a_multibyte_comment_does_not_shift_a_line_number() { + // Lines are counted in bytes by `LineIndex` and in lines by LSP, so + // this is only a regression guard — but the folding math is the place + // an off-by-one would hide. + let text = "// é 🎉\nmodule m;\n wire a;\nendmodule\n"; + assert_eq!(folds(text), vec![(1, 2, "region")]); + } +} diff --git a/crates/vfmt_server/src/main.rs b/crates/vfmt_server/src/main.rs index 925019a..bf83f28 100644 --- a/crates/vfmt_server/src/main.rs +++ b/crates/vfmt_server/src/main.rs @@ -11,6 +11,7 @@ mod code_action; mod completion; mod convert; mod diagnostics; +mod folding; mod format; mod hover; mod lint; @@ -34,10 +35,11 @@ use std::path::PathBuf; use lsp_server::Connection; use lsp_types::{ CodeActionKind, CodeActionOptions, CodeActionProviderCapability, CompletionOptions, - ExecuteCommandOptions, InitializeParams, OneOf, PositionEncodingKind, RenameOptions, - SemanticTokensFullOptions, SemanticTokensLegend, SemanticTokensOptions, - SemanticTokensServerCapabilities, ServerCapabilities, SignatureHelpOptions, - TextDocumentSyncCapability, TextDocumentSyncKind, WorkDoneProgressOptions, + ExecuteCommandOptions, FoldingRangeProviderCapability, InitializeParams, OneOf, + PositionEncodingKind, RenameOptions, SemanticTokensFullOptions, SemanticTokensLegend, + SemanticTokensOptions, SemanticTokensServerCapabilities, ServerCapabilities, + SignatureHelpOptions, TextDocumentSyncCapability, TextDocumentSyncKind, + WorkDoneProgressOptions, }; use crate::server::Server; @@ -73,9 +75,14 @@ fn capabilities() -> ServerCapabilities { definition_provider: Some(OneOf::Left(true)), references_provider: Some(OneOf::Left(true)), // The cursor on a `begin` highlights its own `end`, matched over the - // token stream. The handler declines anything that is not half of a - // pair, which leaves the editor's word highlighting in charge. + // token stream; anywhere else, the symbol under it highlights its own + // other occurrences in this file. The handler declines a position + // that is neither, which leaves the editor's word highlighting in + // charge there. document_highlight_provider: Some(OneOf::Left(true)), + // One range per matched scope pair and per multi-line block comment, + // off the same matcher the rainbow reads. + folding_range_provider: Some(FoldingRangeProviderCapability::Simple(true)), hover_provider: Some(lsp_types::HoverProviderCapability::Simple(true)), document_symbol_provider: Some(OneOf::Left(true)), workspace_symbol_provider: Some(OneOf::Left(true)), @@ -193,6 +200,7 @@ mod tests { assert!(caps.definition_provider.is_some()); assert!(caps.references_provider.is_some()); assert!(caps.document_highlight_provider.is_some()); + assert!(caps.folding_range_provider.is_some()); assert!(caps.hover_provider.is_some()); assert!(caps.document_symbol_provider.is_some()); assert!(caps.workspace_symbol_provider.is_some()); diff --git a/crates/vfmt_server/src/nav.rs b/crates/vfmt_server/src/nav.rs index 905646f..2dfd6a0 100644 --- a/crates/vfmt_server/src/nav.rs +++ b/crates/vfmt_server/src/nav.rs @@ -1,10 +1,12 @@ -//! `textDocument/definition` and `textDocument/references`. +//! `textDocument/definition`, `textDocument/references` and the symbol half of +//! `textDocument/documentHighlight`. -use lsp_types::{Location, Uri}; -use vlog_semantic::Definition; +use lsp_types::{DocumentHighlight, DocumentHighlightKind, Location, Uri}; +use vlog_parser::TextRange; +use vlog_semantic::{Definition, Semantics, SymbolId}; use crate::locate::location; -use crate::state::Workspace; +use crate::state::{Document, Workspace}; use crate::uri::path_to_uri; /// Go-to-definition, through both layers: the in-file symbol table first, then @@ -45,12 +47,20 @@ fn path_to_uri_or_self(ws: &Workspace, uri: &Uri) -> Option { } } -/// Find-all-references, within this file. +/// Find-all-references, across the workspace when the symbol can leave this +/// file and inside it when it cannot. /// -/// Cross-file references are out of scope this round: answering them means -/// resolving every *other* file's references into this one, which is an -/// inverted index the workspace layer does not build. See the feature -/// README's Status/TODO. +/// 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. pub fn references( ws: &Workspace, uri: &Uri, @@ -58,28 +68,135 @@ pub fn references( include_declaration: bool, ) -> Vec { let Some(doc) = ws.document(uri) else { return Vec::new() }; - // The cursor may sit on a use or on the declaration itself; both lead to - // the same symbol. - let symbol_id = doc - .semantics - .reference_at(offset) - .and_then(|r| r.resolved()) - .or_else(|| doc.semantics.symbol_at(offset)); - let Some(symbol_id) = symbol_id else { return Vec::new() }; + if leaves_this_file(ws, doc, offset) { + if let Some(locations) = workspace_references(ws, doc, offset, include_declaration) { + return locations; + } + } + in_file_references(ws, doc, uri, offset, include_declaration) +} +/// Whether an answer for this position could name another file at all. +/// +/// Two ways it can. The cursor sits on a use the workspace overlay answered — +/// an instantiated module, an imported package member — which is by +/// construction cross-file. Or it sits on a declaration the index holds: a +/// file-scope unit, or a member its unit exports. Everything else is a name +/// only this file can spell, and asking the workspace about it would read the +/// whole project to learn nothing. +fn leaves_this_file(ws: &Workspace, doc: &Document, offset: u32) -> bool { + if doc.path.is_none() { + // An `untitled:` buffer is in no index and has no path to hand over. + return false; + } + if let Some(id) = doc.semantics.reference_id_at(offset) { + if let Some(target) = doc.external.get(id) { + return target.best().is_some(); + } + } + let Some(symbol_id) = symbol_at(&doc.semantics, offset) else { return false }; + let Some(symbol) = doc.semantics.symbol(symbol_id) else { return false }; + if !ws.index().units(&symbol.name).is_empty() { + return true; + } + // A member is reachable as `unit::name` or as `.name` in a connection + // list, so the unit that owns the declaring scope is what to ask about. + let owner = doc + .semantics + .scope(symbol.scope) + .and_then(|scope| scope.owner) + .and_then(|owner| doc.semantics.symbol(owner)); + match owner { + Some(owner) => !ws.index().member(&owner.name, &symbol.name).is_empty(), + None => false, + } +} + +/// The workspace-wide answer, or `None` when the engine declined it. +fn workspace_references( + ws: &Workspace, + doc: &Document, + offset: u32, + include_declaration: bool, +) -> Option> { + 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()) +} + +/// The file's own answer: what `Semantics` alone knows about this symbol. +fn in_file_references( + ws: &Workspace, + doc: &Document, + uri: &Uri, + offset: u32, + include_declaration: bool, +) -> Vec { + let Some(symbol_id) = symbol_at(&doc.semantics, offset) else { return Vec::new() }; let Some(target) = path_to_uri_or_self(ws, uri) else { return Vec::new() }; let positions = doc.positions(); - let mut spans: Vec<_> = - doc.semantics.references_of(symbol_id).iter().map(|r| r.name_span).collect(); + occurrences(&doc.semantics, symbol_id, include_declaration) + .into_iter() + .map(|span| Location { uri: target.clone(), range: positions.range(span) }) + .collect() +} + +/// `textDocument/documentHighlight` for a symbol: every occurrence of it in +/// this file, the declaration included. +/// +/// `None` where the cursor is on no symbol, so the editor keeps its own +/// word-occurrence highlighting — the same contract `pairs::highlights` +/// honours, and the reason both live behind one handler. +/// +/// The kind is always `Text`. Telling a read from a write means knowing which +/// side of an assignment — continuous, procedural, port connection, `inout` +/// — a use sits on, and LSP is explicit that plain `Text` is a valid answer. +/// Building that analysis for a highlight colour is not a trade worth making. +pub fn document_highlights(doc: &Document, offset: u32) -> Option> { + let symbol_id = symbol_at(&doc.semantics, offset)?; + let spans = occurrences(&doc.semantics, symbol_id, true); + if spans.is_empty() { + return None; + } + let positions = doc.positions(); + Some( + spans + .into_iter() + .map(|span| DocumentHighlight { + range: positions.range(span), + kind: Some(DocumentHighlightKind::TEXT), + }) + .collect(), + ) +} + +/// The symbol at a position. The cursor may sit on a use or on the +/// declaration itself; both lead to the same symbol. +fn symbol_at(semantics: &Semantics, offset: u32) -> Option { + semantics + .reference_at(offset) + .and_then(|r| r.resolved()) + .or_else(|| semantics.symbol_at(offset)) +} + +/// Every span of one symbol in its own file, sorted and deduplicated. +fn occurrences( + semantics: &Semantics, + symbol_id: SymbolId, + include_declaration: bool, +) -> Vec { + let mut spans: Vec = + semantics.references_of(symbol_id).iter().map(|r| r.name_span).collect(); if include_declaration { - if let Some(symbol) = doc.semantics.symbol(symbol_id) { + if let Some(symbol) = semantics.symbol(symbol_id) { spans.push(symbol.name_span); } } spans.retain(|s| !s.is_empty()); spans.sort_by_key(|s| s.start); spans.dedup(); - spans.into_iter().map(|s| Location { uri: target.clone(), range: positions.range(s) }).collect() + spans } #[cfg(test)] @@ -214,6 +331,240 @@ mod tests { let _ = fs::remove_dir_all(&dir); } + // ------------------------------------------------------------------ + // cross-file references + // ------------------------------------------------------------------ + + const SUB: &str = "module sub (input logic clk);\nendmodule\n"; + const TOP: &str = "module top;\n sub u_a (.clk(1'b0));\n sub u_b (.clk(1'b1));\nendmodule\n"; + const OTHER: &str = "module other;\n sub u_c (.clk(1'b0));\nendmodule\n"; + + /// A three-file workspace, with `which` opened as a buffer. + fn instantiated(tag: &str, which: &str) -> (PathBuf, Workspace, Uri) { + let dir = temp_dir(tag); + for (name, text) in [("sub.sv", SUB), ("top.sv", TOP), ("other.sv", OTHER)] { + fs::write(dir.join(name), text).expect("write"); + } + let mut ws = Workspace::default(); + ws.open_roots(vec![dir.clone()]); + let path = dir.join(which); + let uri = path_to_uri(&path).expect("uri"); + let text = fs::read_to_string(&path).expect("read"); + ws.set_document(uri.clone(), text); + (dir, ws, uri) + } + + /// Every location as `(file name, line)`. + fn places(locations: &[Location]) -> Vec<(String, u32)> { + locations + .iter() + .map(|l| { + let name = l.uri.as_str().rsplit('/').next().unwrap_or("?").to_string(); + (name, l.range.start.line) + }) + .collect() + } + + #[test] + fn a_modules_references_come_from_every_file_that_instantiates_it() { + let (dir, ws, uri) = instantiated("xrefs_decl", "sub.sv"); + let found = references(&ws, &uri, at(SUB, "sub"), true); + assert_eq!( + places(&found), + vec![ + ("other.sv".to_string(), 1), + ("sub.sv".to_string(), 0), + ("top.sv".to_string(), 1), + ("top.sv".to_string(), 2), + ], + "the declaration plus three instantiations" + ); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn references_from_an_instantiation_answer_the_same_set() { + let (dir, ws, uri) = instantiated("xrefs_use", "top.sv"); + let found = references(&ws, &uri, at(TOP, "sub u_b"), true); + assert_eq!( + places(&found), + vec![ + ("other.sv".to_string(), 1), + ("sub.sv".to_string(), 0), + ("top.sv".to_string(), 1), + ("top.sv".to_string(), 2), + ], + "renaming from here would touch exactly these" + ); + 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"); + let found = references(&ws, &uri, at(SUB, "sub"), false); + assert_eq!( + places(&found), + vec![("other.sv".to_string(), 1), ("top.sv".to_string(), 1), ("top.sv".to_string(), 2),] + ); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn a_package_members_references_come_from_every_import_site() { + let dir = temp_dir("xrefs_pkg"); + let pkg = "package p;\n localparam WIDTH = 8;\nendpackage\n"; + let a = "module a;\n import p::*;\n wire [WIDTH-1:0] x;\nendmodule\n"; + let b = "module b;\n wire [p::WIDTH-1:0] y;\nendmodule\n"; + for (name, text) in [("p.sv", pkg), ("a.sv", a), ("b.sv", b)] { + fs::write(dir.join(name), text).expect("write"); + } + let mut ws = Workspace::default(); + ws.open_roots(vec![dir.clone()]); + let uri = path_to_uri(&dir.join("p.sv")).expect("uri"); + ws.set_document(uri.clone(), pkg.to_string()); + + let found = references(&ws, &uri, at(pkg, "WIDTH"), false); + assert_eq!(places(&found), vec![("a.sv".to_string(), 2), ("b.sv".to_string(), 1)]); + + // And from one of the use sites, the same answer plus the declaration. + let a_uri = path_to_uri(&dir.join("a.sv")).expect("uri"); + ws.set_document(a_uri.clone(), a.to_string()); + let from_use = references(&ws, &a_uri, at(a, "WIDTH-1"), true); + assert_eq!( + places(&from_use), + vec![("a.sv".to_string(), 2), ("b.sv".to_string(), 1), ("p.sv".to_string(), 1)] + ); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn a_local_signal_never_asks_the_workspace() { + // The gate, asserted directly: a name the index does not hold cannot + // be named from another file, so `references` must not walk one. The + // functional half is below; this is the half that would otherwise + // only show up as a slow editor. + let dir = temp_dir("xrefs_local"); + let text = "module m;\n wire a;\n assign a = 1;\n assign b = a;\nendmodule\n"; + fs::write(dir.join("m.sv"), text).expect("write"); + fs::write(dir.join("other.sv"), "module other;\n wire a;\nendmodule\n").expect("write"); + let mut ws = Workspace::default(); + ws.open_roots(vec![dir.clone()]); + let uri = path_to_uri(&dir.join("m.sv")).expect("uri"); + ws.set_document(uri.clone(), text.to_string()); + let doc = ws.document(&uri).expect("open"); + + assert!(!leaves_this_file(&ws, doc, at(text, "wire a") + 5), "a net is not indexed"); + assert!(leaves_this_file(&ws, doc, at(text, "module m") + 7), "but the module is"); + + let found = references(&ws, &uri, at(text, "wire a") + 5, true); + assert_eq!( + places(&found), + vec![("m.sv".to_string(), 1), ("m.sv".to_string(), 2), ("m.sv".to_string(), 3)], + "this file only — `other.sv`'s own `a` is a different signal" + ); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn a_name_declared_in_two_files_degrades_references_to_the_in_file_answer() { + // The gate says yes (the index holds `dup` as a unit), but the + // collection refuses it as ambiguous — exactly like a rename would. + // `references` is read-only, so it falls back to what this file + // alone can say, rather than an empty list or a protocol error. + let dir = temp_dir("xrefs_ambiguous"); + let text = "module dup;\n wire w;\nendmodule\n"; + fs::write(dir.join("a.sv"), text).expect("write"); + fs::write(dir.join("b.sv"), text).expect("write"); + let mut ws = Workspace::default(); + ws.open_roots(vec![dir.clone()]); + let a_path = dir.join("a.sv"); + let uri = path_to_uri(&a_path).expect("uri"); + ws.set_document(uri.clone(), text.to_string()); + let doc = ws.document(&uri).expect("open"); + + assert!(leaves_this_file(&ws, doc, at(text, "dup")), "dup is a unit the index holds"); + + let found = references(&ws, &uri, at(text, "dup"), true); + assert_eq!(found.len(), 1, "the in-file declaration only, not empty and not an error"); + assert_eq!(found[0].uri, uri); + assert_eq!(found[0].range.start.line, 0); + + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn a_port_is_reachable_from_a_connection_in_another_file() { + // A module's ports are exactly what the index exports for it, so a + // `.clk(...)` connection elsewhere is a reference to this port. + let (dir, ws, uri) = instantiated("xrefs_port", "sub.sv"); + let found = references(&ws, &uri, at(SUB, "clk"), false); + assert_eq!( + places(&found), + vec![("other.sv".to_string(), 1), ("top.sv".to_string(), 1), ("top.sv".to_string(), 2),] + ); + 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, + // so the in-file answer is the whole answer. + let text = "module m;\n wire a;\n assign a = 1;\nendmodule\n"; + let uri = Uri::from_str("untitled:Untitled-1").expect("uri"); + let mut ws = Workspace::default(); + ws.set_document(uri.clone(), text.to_string()); + let found = references(&ws, &uri, at(text, "wire a") + 5, true); + assert_eq!(found.len(), 2); + assert_eq!(found[0].uri, uri, "reported against the buffer itself"); + } + + // ------------------------------------------------------------------ + // documentHighlight + // ------------------------------------------------------------------ + + #[test] + fn a_signal_highlights_its_declaration_and_every_use() { + let text = "module m;\n wire a;\n assign a = 1;\n assign b = a;\nendmodule\n"; + let (ws, uri) = document(text); + let doc = ws.document(&uri).expect("open"); + let found = document_highlights(doc, at(text, "assign a") + 7).expect("a symbol"); + let lines: Vec = found.iter().map(|h| h.range.start.line).collect(); + assert_eq!(lines, vec![1, 2, 3], "the declaration first, then both uses"); + assert!(found.iter().all(|h| h.kind == Some(DocumentHighlightKind::TEXT))); + } + + #[test] + fn highlighting_works_from_the_declaration_as_well() { + let text = "module m;\n wire a;\n assign a = 1;\nendmodule\n"; + let (ws, uri) = document(text); + let doc = ws.document(&uri).expect("open"); + let found = document_highlights(doc, at(text, "wire a") + 5).expect("a symbol"); + assert_eq!(found.len(), 2); + assert_eq!(found[0].range.start.line, 1); + } + + #[test] + fn highlight_ranges_are_utf16() { + let text = "module m;\n wire a; // é 🎉\n assign a = 1;\nendmodule\n"; + let (ws, uri) = document(text); + let doc = ws.document(&uri).expect("open"); + let found = document_highlights(doc, at(text, "wire a") + 5).expect("a symbol"); + assert_eq!(found[0].range.start.character, 7); + assert_eq!(found[1].range.start.character, 9); + } + + #[test] + fn a_position_on_no_symbol_declines_rather_than_answering_nothing() { + // `None`, not an empty list: an empty list tells the editor to stop + // drawing its own word highlighting. + let text = "module m;\n wire a;\nendmodule\n"; + let (ws, uri) = document(text); + let doc = ws.document(&uri).expect("open"); + assert!(document_highlights(doc, at(text, "wire")).is_none(), "a keyword"); + assert!(document_highlights(doc, 0).is_none(), "the `module` keyword"); + } + #[test] fn a_package_import_resolves_into_the_packages_file() { let dir = temp_dir("pkg"); diff --git a/crates/vfmt_server/src/server.rs b/crates/vfmt_server/src/server.rs index 8da5bc6..4b5eac4 100644 --- a/crates/vfmt_server/src/server.rs +++ b/crates/vfmt_server/src/server.rs @@ -15,17 +15,18 @@ use lsp_types::notification::{ }; use lsp_types::request::{ CodeActionRequest, Completion, DocumentHighlightRequest, DocumentSymbolRequest, ExecuteCommand, - Formatting, GotoDefinition, HoverRequest, PrepareRenameRequest, RangeFormatting, References, - Rename, Request as _, SemanticTokensFullRequest, SignatureHelpRequest, WorkspaceSymbolRequest, + FoldingRangeRequest, Formatting, GotoDefinition, HoverRequest, PrepareRenameRequest, + RangeFormatting, References, Rename, Request as _, SemanticTokensFullRequest, + SignatureHelpRequest, WorkspaceSymbolRequest, }; use lsp_types::{ CodeActionKind, CodeActionParams, CompletionParams, DidChangeConfigurationParams, DidChangeTextDocumentParams, DidCloseTextDocumentParams, DidOpenTextDocumentParams, DidSaveTextDocumentParams, DocumentFormattingParams, DocumentHighlightParams, DocumentRangeFormattingParams, DocumentSymbolParams, DocumentSymbolResponse, - ExecuteCommandParams, GotoDefinitionParams, GotoDefinitionResponse, HoverParams, - LogMessageParams, MessageType, Position, PublishDiagnosticsParams, ReferenceParams, - RenameParams, SemanticTokensParams, SemanticTokensResult, ShowMessageParams, + ExecuteCommandParams, FoldingRangeParams, GotoDefinitionParams, GotoDefinitionResponse, + HoverParams, LogMessageParams, MessageType, Position, PublishDiagnosticsParams, + ReferenceParams, RenameParams, SemanticTokensParams, SemanticTokensResult, ShowMessageParams, SignatureHelpParams, TextDocumentPositionParams, Uri, WorkspaceSymbolParams, WorkspaceSymbolResponse, }; @@ -34,8 +35,8 @@ use serde_json::Value; use crate::state::Workspace; use crate::{ - code_action, completion, diagnostics, format, hover, nav, pairs, ports, rename, settings, - signature, symbols, tokens, + code_action, completion, diagnostics, folding, format, hover, nav, pairs, ports, rename, + settings, signature, symbols, tokens, }; /// Everything the server owns. @@ -116,11 +117,13 @@ impl Server { .unwrap_or_default(); to_value(locations) }), - // A cursor that is not on half of a matched pair answers `null` - // rather than an empty list: an empty list means "no occurrences - // anywhere", which suppresses the editor's own word highlighting, - // and losing that everywhere except on `begin` would be a poor - // trade for gaining it on `begin`. + // Two answers behind one request: a scope keyword pairs with its + // own closer, and anything else is a symbol whose other + // occurrences in this file are what to draw. A cursor that is + // neither answers `null` rather than an empty list — an empty list + // means "no occurrences anywhere", which suppresses the editor's + // own word highlighting, and losing that everywhere would be a + // poor trade for gaining this. DocumentHighlightRequest::METHOD => { decode(request).and_then(|p: DocumentHighlightParams| { let at = p.text_document_position_params; @@ -128,10 +131,17 @@ impl Server { let found = self.offset(&uri, position).and_then(|offset| { let doc = self.workspace.document(&uri)?; pairs::highlights(doc, offset) + .or_else(|| nav::document_highlights(doc, offset)) }); found.map_or(Ok(Value::Null), to_value) }) } + FoldingRangeRequest::METHOD => decode(request).and_then(|p: FoldingRangeParams| { + match self.workspace.document(&p.text_document.uri) { + Some(doc) => to_value(folding::folding_ranges(doc)), + None => Ok(Value::Null), + } + }), SemanticTokensFullRequest::METHOD => { decode(request).and_then(|p: SemanticTokensParams| { match self.workspace.document(&p.text_document.uri) { diff --git a/crates/vfmt_server/tests/e2e.rs b/crates/vfmt_server/tests/e2e.rs index 3b45e85..92d80ab 100644 --- a/crates/vfmt_server/tests/e2e.rs +++ b/crates/vfmt_server/tests/e2e.rs @@ -1485,3 +1485,114 @@ fn a_template_completion_round_trips_over_the_wire() { let _ = std::fs::remove_dir_all(&dir); } + +/// The three navigation capabilities of round M7, over the wire in one +/// session: a reference set that spans two files, the folds of a buffer, and +/// the occurrences of a signal inside it. +const NAV_SUB: &str = "module sub (input logic clk);\nendmodule\n"; +const NAV_TOP: &str = concat!( + "module top;\n", // 0 + " logic clk;\n", // 1 + " sub u_a (.clk(clk));\n", // 2 + " assign clk = 1'b0;\n", // 3 + "endmodule\n", // 4 +); + +#[test] +fn cross_file_references_folding_and_highlights_round_trip_over_the_wire() { + let dir = temp_dir("nav"); + let sub = dir.join("sub.sv"); + std::fs::write(&sub, NAV_SUB).expect("write"); + let top = dir.join("top.sv"); + std::fs::write(&top, NAV_TOP).expect("write"); + let root = format!("file://{}", dir.display()); + let uri = format!("file://{}", top.display()); + let sub_uri = format!("file://{}", sub.display()); + + let session = [ + frame(&format!( + r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"# + )), + frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), + frame(&format!( + r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, + serde_json::to_string(NAV_TOP).expect("json") + )), + // The `sub` of the instantiation on line 2: its declaration lives in + // the other file, and only a cross-file answer can say so. + frame(&format!( + r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/references","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":2,"character":2}},"context":{{"includeDeclaration":true}}}}}}"# + )), + frame(&format!( + r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/references","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":2,"character":2}},"context":{{"includeDeclaration":false}}}}}}"# + )), + frame(&format!( + r#"{{"jsonrpc":"2.0","id":4,"method":"textDocument/foldingRange","params":{{"textDocument":{{"uri":"{uri}"}}}}}}"# + )), + // The `clk` declared on line 1 — a plain local signal, so the answer + // is this file's occurrences of it and nothing else. + frame(&format!( + r#"{{"jsonrpc":"2.0","id":5,"method":"textDocument/documentHighlight","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":1,"character":8}}}}}}"# + )), + frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), + frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), + ] + .concat(); + + let messages = talk(&session); + + let initialize = messages.iter().find(|m| m["id"] == 1).expect("initialize response"); + let capabilities = &initialize["result"]["capabilities"]; + assert_eq!(capabilities["referencesProvider"], serde_json::json!(true)); + assert_eq!(capabilities["foldingRangeProvider"], serde_json::json!(true)); + assert_eq!(capabilities["documentHighlightProvider"], serde_json::json!(true)); + + let response = |id: u32| -> &serde_json::Value { + messages.iter().find(|m| m["id"] == id).unwrap_or_else(|| panic!("no {id}: {messages:#?}")) + }; + let places = |id: u32| -> Vec<(String, u64, u64)> { + response(id)["result"] + .as_array() + .unwrap_or_else(|| panic!("response {id} is not a list: {:#?}", response(id))) + .iter() + .map(|l| { + ( + l["uri"].as_str().expect("uri").to_string(), + l["range"]["start"]["line"].as_u64().expect("line"), + l["range"]["start"]["character"].as_u64().expect("character"), + ) + }) + .collect() + }; + assert_eq!( + places(2), + vec![(sub_uri.clone(), 0, 7), (uri.clone(), 2, 2)], + "the module declaration in sub.sv, and the instantiation here" + ); + assert_eq!(places(3), vec![(uri.clone(), 2, 2)], "without the declaration"); + + let folds = response(4)["result"].as_array().expect("a folding list"); + assert_eq!(folds.len(), 1, "the module, and nothing that never closed: {folds:#?}"); + assert_eq!(folds[0]["startLine"], 0); + assert_eq!(folds[0]["endLine"], 3, "one short of `endmodule`, which stays visible"); + assert_eq!(folds[0]["kind"], "region"); + + let highlights = response(5)["result"].as_array().expect("a highlight list"); + let at: Vec<(u64, u64)> = highlights + .iter() + .map(|h| { + ( + h["range"]["start"]["line"].as_u64().expect("line"), + h["range"]["start"]["character"].as_u64().expect("character"), + ) + }) + .collect(); + assert_eq!( + at, + vec![(1, 8), (2, 16), (3, 9)], + "the declaration, the connected expression and the assignment — not the `.clk` port name" + ); + assert!(highlights.iter().all(|h| h["kind"] == 1), "DocumentHighlightKind.Text"); + + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/vlog_refactor/src/lib.rs b/crates/vlog_refactor/src/lib.rs index cd1f0bb..7a90587 100644 --- a/crates/vlog_refactor/src/lib.rs +++ b/crates/vlog_refactor/src/lib.rs @@ -18,17 +18,23 @@ //! `docs/features/refactor-ports/README.md` for the refusal lists and the //! verification stories. //! -//! One member of the crate edits nothing: [`instantiation_plan`] answers "what +//! Two members of the crate edit nothing. [`instantiation_plan`] answers "what //! would an instantiation of this module look like here", which is rope's -//! type-hinting-drives-completion translated to Verilog. It produces text for +//! type-hinting-drives-completion translated to Verilog; it produces text for //! the caller to offer, never a [`RefactorEdit`], so it needs no verification //! pass — see `docs/features/refactor-instantiate/README.md`. +//! [`find_references`] answers "where else is this symbol", which is the +//! *first half* of a rename: same cursor resolution, same cross-file walk, +//! spans instead of edits — see `docs/features/references-nav/README.md`. mod check; mod instantiate; mod ports; +mod references; mod rename; +pub use references::find_references; + pub use instantiate::{ instantiation_plan, module_definition, module_names, InstantiationPlan, Layout, PlanParam, PlanPort, Site, diff --git a/crates/vlog_refactor/src/references.rs b/crates/vlog_refactor/src/references.rs new file mode 100644 index 0000000..892d5e9 --- /dev/null +++ b/crates/vlog_refactor/src/references.rs @@ -0,0 +1,182 @@ +//! Find-all-references: the read-only half of what a rename already computes. +//! +//! A rename resolves the cursor to a *declaration* and then collects every +//! occurrence of that declaration across the in-scope files. Listing those +//! occurrences is the same walk with the edits left off, so it is the same +//! code — this module only decides what to do with the spans. The sharing is +//! the point, not the lines it saves: a reference list that disagreed with +//! what a rename would touch would be a lie about what vfmt is going to do. + +use std::path::{Path, PathBuf}; + +use vlog_parser::span::TextRange; + +use crate::rename::Scope; + +/// Every occurrence of the symbol at `offset` in `file`, across `files`. +/// +/// `files` is the in-scope set — path and current text, open buffers already +/// overlaying disk — exactly what [`crate::rename`] takes. The result is +/// sorted by path and then by position, and every span slices back to the +/// name it claims. +/// +/// An `Err` is the sentence a rename at the same position would refuse with +/// (nothing here to name, a name declared in two indexed files, a use nothing +/// resolves). A caller that only wants to draw highlights can fall back to +/// the file's own answer rather than showing it. +pub fn find_references( + files: &[(PathBuf, String)], + file: &Path, + offset: u32, + include_declaration: bool, +) -> Result, String> { + let mut scope = Scope::build(files); + let target = scope.locate(file, offset)?; + let declaration = scope.declaration_span(&target); + let found = scope.collect_occurrences(&target)?; + + let mut out: Vec<(PathBuf, TextRange)> = Vec::new(); + for (i, mut spans) in found { + let (Some(path), Some(text)) = (scope.path(i), scope.text(i)) else { continue }; + if !include_declaration && i == target.file { + if let Some(span) = declaration { + spans.retain(|s| *s != span); + } + } + // The semantic layer promises a name span slices back to its own + // name. A span that does not is not a place to send an editor, and + // dropping it costs one string comparison per occurrence. + spans.retain(|s| text.get(s.as_range()) == Some(target.name.as_str())); + spans.sort_by_key(|s| (s.start, s.end)); + spans.dedup(); + out.extend(spans.into_iter().map(|span| (path.to_path_buf(), span))); + } + out.sort_by(|a, b| (a.0.as_path(), a.1.start).cmp(&(b.0.as_path(), b.1.start))); + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + const SUB: &str = "module sub (input logic clk);\nendmodule\n"; + const TOP: &str = "module top;\n sub u_a (.clk(1'b0));\n sub u_b (.clk(1'b1));\nendmodule\n"; + const OTHER: &str = "module other;\n sub u_c (.clk(1'b0));\nendmodule\n"; + + fn files() -> Vec<(PathBuf, String)> { + vec![ + (PathBuf::from("/w/sub.sv"), SUB.to_string()), + (PathBuf::from("/w/top.sv"), TOP.to_string()), + (PathBuf::from("/w/other.sv"), OTHER.to_string()), + ] + } + + fn at(text: &str, needle: &str) -> u32 { + text.find(needle).expect("needle present") as u32 + } + + /// `(file name, byte start)` of every hit, which is enough to read. + fn hits(found: &[(PathBuf, TextRange)]) -> Vec<(String, u32)> { + found + .iter() + .map(|(path, span)| { + (path.file_name().and_then(|n| n.to_str()).unwrap_or("?").to_string(), span.start) + }) + .collect() + } + + #[test] + fn a_modules_references_come_from_every_file_that_instantiates_it() { + let files = files(); + let found = + find_references(&files, Path::new("/w/sub.sv"), at(SUB, "sub"), true).expect("found"); + assert_eq!( + hits(&found), + vec![ + ("other.sv".to_string(), at(OTHER, "sub u_c")), + ("sub.sv".to_string(), at(SUB, "sub")), + ("top.sv".to_string(), at(TOP, "sub u_a")), + ("top.sv".to_string(), at(TOP, "sub u_b")), + ] + ); + } + + #[test] + fn the_answer_is_the_same_from_an_instantiation_as_from_the_declaration() { + let files = files(); + let from_declaration = + find_references(&files, Path::new("/w/sub.sv"), at(SUB, "sub"), true).expect("found"); + let from_use = + find_references(&files, Path::new("/w/top.sv"), at(TOP, "sub u_b"), true).expect("f"); + assert_eq!(hits(&from_declaration), hits(&from_use)); + } + + #[test] + fn include_declaration_drops_only_the_declarations_own_name() { + let files = files(); + let without = + find_references(&files, Path::new("/w/sub.sv"), at(SUB, "sub"), false).expect("found"); + assert_eq!( + hits(&without), + vec![ + ("other.sv".to_string(), at(OTHER, "sub u_c")), + ("top.sv".to_string(), at(TOP, "sub u_a")), + ("top.sv".to_string(), at(TOP, "sub u_b")), + ] + ); + } + + #[test] + fn a_package_member_is_found_at_every_import_site() { + let pkg = "package p;\n localparam WIDTH = 8;\nendpackage\n"; + let a = "module a;\n import p::*;\n wire [WIDTH-1:0] x;\nendmodule\n"; + let b = "module b;\n wire [p::WIDTH-1:0] y;\nendmodule\n"; + let files = vec![ + (PathBuf::from("/w/p.sv"), pkg.to_string()), + (PathBuf::from("/w/a.sv"), a.to_string()), + (PathBuf::from("/w/b.sv"), b.to_string()), + ]; + let found = + find_references(&files, Path::new("/w/p.sv"), at(pkg, "WIDTH"), false).expect("found"); + assert_eq!( + hits(&found), + vec![("a.sv".to_string(), at(a, "WIDTH-1")), ("b.sv".to_string(), at(b, "WIDTH-1")),] + ); + } + + #[test] + fn a_local_signal_is_answered_from_its_own_file_only() { + let m = "module m;\n wire a;\n assign a = 1;\nendmodule\n"; + let other = "module other;\n wire a;\n assign a = 0;\nendmodule\n"; + let files = vec![ + (PathBuf::from("/w/m.sv"), m.to_string()), + (PathBuf::from("/w/other.sv"), other.to_string()), + ]; + let found = + find_references(&files, Path::new("/w/m.sv"), at(m, "wire a") + 5, true).expect("f"); + assert_eq!( + hits(&found), + vec![ + ("m.sv".to_string(), at(m, "wire a") + 5), + ("m.sv".to_string(), at(m, "assign a") + 7), + ] + ); + } + + #[test] + fn a_name_two_files_declare_is_refused_rather_than_guessed() { + let files = vec![ + (PathBuf::from("/w/a.sv"), "module dup;\nendmodule\n".to_string()), + (PathBuf::from("/w/b.sv"), "module dup;\nendmodule\n".to_string()), + ]; + let message = + find_references(&files, Path::new("/w/a.sv"), 7, true).expect_err("ambiguous"); + assert!(message.contains("more than one indexed file"), "{message}"); + } + + #[test] + fn a_position_on_nothing_is_refused() { + let files = files(); + assert!(find_references(&files, Path::new("/w/sub.sv"), 0, true).is_err(), "the keyword"); + } +} diff --git a/crates/vlog_refactor/src/rename.rs b/crates/vlog_refactor/src/rename.rs index b277830..40a0680 100644 --- a/crates/vlog_refactor/src/rename.rs +++ b/crates/vlog_refactor/src/rename.rs @@ -208,7 +208,7 @@ impl<'a> Scope<'a> { /// file, or on a use whose declaration lives in another file — all three /// end here, which is what makes renaming from a reference identical to /// renaming from the declaration. - fn locate(&mut self, file: &Path, offset: u32) -> Result { + pub(crate) fn locate(&mut self, file: &Path, offset: u32) -> Result { let Some(here) = self.index_of(file) else { return Err(format!( "{} is not one of the files vfmt indexes; nothing outside the project scope can be renamed.", @@ -323,26 +323,32 @@ impl<'a> Scope<'a> { self.declaration(file, symbol, cursor) } + /// Where the target declaration spells its own name. + pub(crate) fn declaration_span(&mut self, target: &Target) -> Option { + self.analysis(target.file) + .and_then(|a| a.semantics.symbol(target.symbol).map(|s| s.name_span)) + } + /// Every occurrence of the declaration in every in-scope file: its own /// name, its in-file uses, and the cross-file uses the overlay attributes - /// to it. - fn collect_edits( + /// to it. Per file, in the order the walk found them. + /// + /// Shared with [`crate::find_references`], which wants the same set + /// without the edits: an occurrence a rename would change and a reference + /// list that does not name it would be two answers about one symbol. + pub(crate) fn collect_occurrences( &mut self, target: &Target, - new_name: &str, - ) -> Result)>, String> { + ) -> Result)>, String> { let Some(def_file) = self.file_id(target.file) else { return Err("the declaring file is not indexed.".to_string()); }; - let Some(def_span) = self - .analysis(target.file) - .and_then(|a| a.semantics.symbol(target.symbol).map(|s| s.name_span)) - else { + let Some(def_span) = self.declaration_span(target) else { return Err(NOTHING_HERE.to_string()); }; let is_ours = |def: &Def| def.file == def_file && def.name_span == def_span; - let mut out: Vec<(usize, Vec)> = Vec::new(); + let mut out: Vec<(usize, Vec)> = Vec::new(); for i in 0..self.len() { let Some(text) = self.text(i) else { continue }; // A file that does not spell the name cannot reference it: the @@ -373,6 +379,21 @@ impl<'a> Scope<'a> { _ => {} } } + out.push((i, spans)); + } + Ok(out) + } + + /// The rename's own view of [`Scope::collect_occurrences`]: the same + /// spans, checked and turned into replacements. + fn collect_edits( + &mut self, + target: &Target, + new_name: &str, + ) -> Result)>, String> { + let found = self.collect_occurrences(target)?; + let mut out: Vec<(usize, Vec)> = Vec::new(); + for (i, spans) in found { let edits = self.edits_from_spans(i, spans, &target.name, new_name)?; if !edits.is_empty() { out.push((i, edits)); diff --git a/docs/features/refactor/README.md b/docs/features/refactor/README.md index bd39225..72a8bf5 100644 --- a/docs/features/refactor/README.md +++ b/docs/features/refactor/README.md @@ -141,15 +141,15 @@ Found by auditing the shipped capability set against the LSP end goal (Pylance/ruff parity), the code's own "not shipped" notes, and what M1–M6 built but nothing consumes yet. Ordered by value ÷ cost: -- [ ] **Cross-file find-all-references** — `textDocument/references` is +- [x] **Cross-file find-all-references** — `textDocument/references` is still in-file only (nav.rs:50; vfmt-server README names it "not done"), yet M2's rename already collects cross-file reference sets in `vlog_refactor`. Rename can change what references can't even list. Reuse M2's collection for the references answer — mostly wiring. -- [ ] **Folding ranges** — `pairs.rs` already computes every +- [x] **Folding ranges** — `pairs.rs` already computes every begin/end/module/generate range for the rainbow; `foldingRange` is the same data on a standard capability. Cheapest win on this list. -- [ ] **Document highlight** — cursor on a symbol highlights its other +- [x] **Document highlight** — cursor on a symbol highlights its other occurrences; one `references_of` call, no new analysis. - [ ] **Inlay hints for ordered connections** — `u (clk, rst_n, data)` shows `.clk:`/`.rst_n:` ghost labels from the instantiated module's @@ -261,6 +261,7 @@ commit — in order: - [x] M5 completion-core — done, QA clean first pass, reviewed - [x] M6 completion-templates — done, QA clean first pass, reviewed - [x] Backlog triage after M6 — LSP-parity gap list added, 2026-08-24 +- [x] M7 references-nav — done, QA clean first pass, reviewed ## Work log diff --git a/docs/features/references-nav/README.md b/docs/features/references-nav/README.md new file mode 100644 index 0000000..155d999 --- /dev/null +++ b/docs/features/references-nav/README.md @@ -0,0 +1,478 @@ +# 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 vfmt 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/vfmt-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: + +```rust +pub fn find_references( + files: &[(PathBuf, String)], + file: &Path, + offset: u32, + include_declaration: bool, +) -> Result, 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 `vfmt_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 vfmt 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, `vfmt/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 + +- [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::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. +- [x] `server.rs`: `documentHighlight` tries the scope pair first, the symbol + second, and still declines both with `null`. +- [x] `folding.rs` — one range per matched pair, plus multi-line block + comments, 15 tests. +- [x] `foldingRangeProvider` advertised in `main.rs`. +- [x] e2e: one session covering cross-file references (both + `includeDeclaration` values), `foldingRange` and `documentHighlight`. +- [x] `docs/features/vfmt-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/vfmt-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 vfmt 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`, `vfmt_core`, + `crates/vfmt`, `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/vfmt-server`: OK. +Files added: `crates/vlog_refactor/src/references.rs`, +`crates/vfmt_server/src/folding.rs`, this README. Files edited: +`crates/vlog_refactor/src/{lib.rs,rename.rs}`, +`crates/vfmt_server/src/{main.rs,server.rs,nav.rs}`, +`crates/vfmt_server/tests/e2e.rs`, `docs/features/vfmt-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 + `touch`ing 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/vfmt-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)` 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 (`vfmt_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/vfmt_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/vfmt-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 +`vfmt-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. diff --git a/docs/features/vfmt-server/README.md b/docs/features/vfmt-server/README.md index da09c0f..f2cc895 100644 --- a/docs/features/vfmt-server/README.md +++ b/docs/features/vfmt-server/README.md @@ -22,7 +22,9 @@ 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 | | `textDocument/hover` | `DefineTable`, `Semantics`, `WorkspaceIndex` | Macro body, or declaration kind + snippet | | `textDocument/definition` | `Semantics` then `ExternalResolutions` | `Ambiguous` returns every location | -| `textDocument/references` | `Semantics::references_of` | In-file only this round | +| `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/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 | | `textDocument/prepareRename` | `vlog_refactor::prepare_rename` | Declines with the engine's own sentence (`RequestFailed`), so the box never opens on a rename that would fail | | `textDocument/rename` | `vlog_refactor::rename` | Cross-file `WorkspaceEdit` (`changes`); warnings go out on `window/logMessage`; refusals are `RequestFailed`. See `docs/features/refactor-rename/README.md` | @@ -45,7 +47,12 @@ their Safe fixes — see `docs/features/server-lint/README.md`**, refactoring plan): `completionProvider` expands a module name at item position into a full instantiation skeleton and `signatureHelpProvider` names the ports inside a connection list — see -`docs/features/refactor-instantiate/README.md`**, and cross-file references. +`docs/features/refactor-instantiate/README.md`**, ~~and cross-file +references~~ **delivered by references-nav (M7): `textDocument/references` +now routes through the same collection a rename runs, so what vfmt lists and +what vfmt would edit are one answer — see +`docs/features/references-nav/README.md`, which also brought +`documentHighlight` for symbols and `foldingRange`.** (`vfmt.toml` discovery and `.gitignore`-aware indexing, deferred when this was written, were delivered by vfmt-core-lift the same day — lead note.) @@ -256,10 +263,19 @@ spans, and `defines::{collect_defines, Define, DefineTable}`. **Consumed from `vlog_semantic`:** `analyze`, `Semantics::{symbol_at, reference_at, references_of, document_symbols, symbol, symbols, references, -reference_id_at}`, `Symbol { name, kind, name_span, decl_span, child_scope }`, -`SymbolKind`, `Resolution`, `DocumentSymbol`, and the workspace layer — -`WorkspaceIndex::{build, path, find_define, workspace_symbols}`, -`resolve_external`, `ExternalResolutions::definition_of`, `Definition`, `Def`. +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`, +`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, String>`, which is +the cross-file half of `textDocument/references`. Every one of them takes the +same `Workspace::sources()` file set. **Consumed from `vlog_formatter`:** `format_source(&str, &Config) -> Result` and `Config { max_width, indent_width }`. @@ -414,10 +430,16 @@ list to `vlog_parser::KEYWORDS`. Rationale and inventory: signature help delivered by **refactor-instantiate** (M4), both served from `vlog_refactor::instantiation_plan` so Vim gets the same answers. `docs/features/refactor-instantiate/README.md`. -- [ ] **Not done:** cross-file references. `references_of` is per-file, and +- [x] ~~**Not done:** cross-file references. `references_of` is per-file, and 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. + 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`. + `docs/features/references-nav/README.md`. - [x] ~~**Not done:**~~ `vfmt.toml` discovery, `.gitignore`-aware indexing — delivered by vfmt-core-lift (both Handshakes below marked DELIVERED). - [ ] **Not done:** editor packaging (the VS Code extension and the