diff --git a/crates/lucisv_server/src/hover.rs b/crates/lucisv_server/src/hover.rs index 0ec2886..ac605c3 100644 --- a/crates/lucisv_server/src/hover.rs +++ b/crates/lucisv_server/src/hover.rs @@ -15,7 +15,6 @@ use vlog_parser::token::Token; use vlog_parser::{LineIndex, TextRange}; use vlog_semantic::{Def, Definition, FileId, Symbol}; -use crate::convert::Positions; use crate::expand::{self, Expansion}; use crate::locate::{display_name, line_number}; use crate::nav::indexed_def_for_symbol; @@ -180,18 +179,46 @@ fn symbol_hover(ws: &Workspace, doc: &Document, offset: u32) -> Option { // `declaration_snippet` checks the other file's text against. let name = doc.semantics.reference_at(offset).map(|r| r.name.as_str()); let mut parts = Vec::with_capacity(defs.len()); + // One read per *file*, not per card: a closed file's heading line + // and its snippet below both come from this memoized view, and a + // hover can name the same file several times (two modules with + // one name, a package and its member). + let mut disk: Option<(std::path::PathBuf, String, LineIndex)> = None; for def in defs { let label = kind_label(def.kind); - let where_ = ws - .index() - .path(def.file) - .map(|path| match line_number(ws, path, def.name_span.start) { - Some(line) => format!("{}:{line}", display_name(path)), - None => display_name(path), - }) - .unwrap_or_else(|| "the workspace".to_string()); + let path = ws.index().path(def.file).map(|p| p.to_path_buf()); + let mut where_ = None; + let mut snippet = None; + if let Some(path) = path.as_ref() { + if ws.document_for_path(path).is_some() { + // The live path reads the open buffer — `live_symbol` + // resolves the current span, and its guards stay. + where_ = line_number(ws, path, def.name_span.start) + .map(|line| format!("{}:{line}", display_name(path))); + snippet = name.and_then(|name| declaration_snippet(ws, def, name)); + } else if let Some((text, index)) = disk_view(ws, path, &mut disk) { + // The disk path: the same read serves the heading and + // the snippet, under the same `spells_exactly` guard + // `declaration_snippet` applies. + where_ = Some(format!( + "{}:{}", + display_name(path), + index.line_col(def.name_span.start).0 + )); + snippet = name.and_then(|name| { + spells_exactly(text, def.name_span, name) + .then(|| { + fenced_sections(text, index, def.name_span, def.detail_span) + }) + .flatten() + }); + } else { + where_ = Some(display_name(path)); + } + } + let where_ = where_.unwrap_or_else(|| "the workspace".to_string()); let mut part = format!("**{label}** — declared in `{where_}`"); - if let Some(snippet) = name.and_then(|name| declaration_snippet(ws, def, name)) { + if let Some(snippet) = snippet { part.push_str(&snippet); } parts.push(part); @@ -201,15 +228,150 @@ fn symbol_hover(ws: &Workspace, doc: &Document, offset: u32) -> Option { } } -/// A local declaration: what it is, and the lines it was written on. +/// A local declaration: what it is, and the lines it was written on — with +/// the comment that documents those lines attached (`attached_lines`). A +/// non-ANSI port is named in the header and *finished* in the body +/// (`input signed [31:0] data_in;`), so its card has two sections: the +/// header's, then the body's, each carrying its own comment. fn local_text(doc: &Document, symbol: &Symbol) -> String { - let snippet = doc.positions().whole_lines(symbol.decl_span); - format!( - "**{}** `{}`\n\n```systemverilog\n{}\n```", - kind_label(symbol.kind), - symbol.name, - snippet.trim_end() - ) + let head = format!("**{}** `{}`\n\n", kind_label(symbol.kind), symbol.name); + let body = fenced_sections(&doc.text, &doc.line_index, symbol.decl_span, symbol.detail_span) + .unwrap_or_default(); + format!("{head}{body}") +} + +/// The fenced half of a hover card: one section for a declaration complete +/// where it is named, two — header, then body detail — for a non-ANSI split +/// port. Each section is the declaration's own lines plus its attached +/// comment, cut to card size independently. +fn fenced_sections( + text: &str, + index: &LineIndex, + primary: TextRange, + detail: Option, +) -> Option { + let section = |span: TextRange| fenced(&attached_lines(text, index, span)).unwrap_or_default(); + let first = section(primary); + let second = detail.map(section).filter(|s| !s.is_empty()); + let joined = match second { + Some(second) if !first.is_empty() => format!("{first}\n\n{second}"), + Some(second) => second, + None => first, + }; + (!joined.is_empty()).then_some(joined) +} + +// ---------------------------------------------------------------------- +// comments attached to a declaration +// ---------------------------------------------------------------------- + +/// The lines a declaration was written on, plus every comment that documents +/// it, in source order. The three sources are independent — a declaration can +/// carry all three at once: +/// +/// * a comment on the declaration's own line is already in those lines; +/// * the comment-only lines directly **above** attach — the walk stops at the +/// first line that is not comment-only, so a line carrying another port +/// (and its trailing comment) never contributes; +/// * the comment-only lines directly **below** attach, provided nothing else +/// could claim them: the first line after the block must be one +/// `only_a_closer_on` positively recognises, or the end of the file. +/// +/// Only `//` lines and `/* ... */` complete on one line count; the interior +/// of a multi-line block comment is indistinguishable from code without +/// lexing, and a hover card that guessed would be the wrong-line lie the +/// snippet guards exist to prevent. +fn attached_lines(text: &str, index: &LineIndex, span: TextRange) -> String { + let Some((first, last)) = section_lines(index, span) else { + return String::new(); + }; + let line = |n: u32| { + index + .line_range(n) + .and_then(|r| text.get(r.start as usize..r.end as usize)) + // A line's range ends before its `\n` but *after* the `\r` a CRLF + // file puts in front of it, which would land in the middle of the + // card's fenced block. Display text only; the buffer is untouched. + .map(|line| line.strip_suffix('\r').unwrap_or(line)) + }; + let decl: Vec<&str> = (first..=last).map(|n| line(n).unwrap_or("")).collect(); + + let mut above: Vec<&str> = Vec::new(); + let mut n = first.saturating_sub(1); + while n >= 1 && comment_only(line(n).unwrap_or("")) { + above.push(line(n).unwrap_or("")); + n -= 1; + } + + let mut below: Vec<&str> = Vec::new(); + let mut n = last + 1; + while comment_only(line(n).unwrap_or("")) { + below.push(line(n).unwrap_or("")); + n += 1; + } + // The guard on the below half: the block is this declaration's only when + // the line after it cannot be another declaration — a closer, or the end + // of the file, where nothing follows to claim it. Anything else, a + // wrapped declaration's bare `input` included, is another declaration's + // leading comment. + let claimed_by_nothing_else = match line(n) { + Some(next) => only_a_closer_on(next), + None => true, + }; + if !claimed_by_nothing_else { + below.clear(); + } + + above.into_iter().rev().chain(decl).chain(below).collect::>().join("\n") +} + +/// The 1-based (first, last) line numbers a span's lines cover. +fn section_lines(index: &LineIndex, span: TextRange) -> Option<(u32, u32)> { + if span.end <= span.start { + return None; + } + let first = index.line_col(span.start).0; + let last = index.line_col(span.end - 1).0; + Some((first, last)) +} + +/// Whether a line is nothing but a comment. +fn comment_only(line: &str) -> bool { + let trimmed = line.trim(); + trimmed.starts_with("//") + || (trimmed.starts_with("/*") && trimmed.ends_with("*/") && trimmed.len() >= 4) +} + +/// Whether a line carries nothing but a closer — the only shape that lets a +/// comment block above it belong to the declaration *before* it. +/// +/// The question a below-comment asks is "could anything after this block +/// claim it?", and the only honest textual answer is a whitelist: a line is +/// safe when every word on it is a block terminator, which includes a line +/// with no words at all (`);`, a blank line, punctuation). Everything else — +/// a name, a direction keyword, the bare `input` a *wrapped* declaration +/// begins with — reads as another declaration and the comment stays with it. +/// +/// The bias is the point. This is textual on purpose: the disk path of a +/// cross-file hover has no parse to ask, and only a false "another +/// declaration is here" is safe, because it merely declines to attach a +/// comment — the direction that cannot lie. A false "nothing here" shows one +/// declaration's comment on another's card, which is the one thing this +/// feature promises never to do. +fn only_a_closer_on(line: &str) -> bool { + let code = match line.find("//") { + Some(at) => &line[..at], + None => line, + }; + code.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_' || c == '$')) + .filter(|word| !word.is_empty()) + .all(is_closer_word) +} + +/// The words that end a block a declaration can live in, and nothing else: +/// what a comment block below a *last* declaration is followed by. +fn is_closer_word(word: &str) -> bool { + matches!(word, "end" | "endmodule" | "endinterface" | "endtask" | "endfunction") } // ---------------------------------------------------------------------- @@ -221,53 +383,72 @@ fn local_text(doc: &Document, symbol: &Symbol) -> String { const SNIPPET_LINES: usize = 5; const SNIPPET_CHARS: usize = 400; -/// The source of a declaration in another file, fenced for the card. +/// The source of a declaration in an **open** buffer, fenced for the card. /// /// The index holds only `{file, name_span, kind}` and no text /// (`docs/features/workspace-index/README.md`), so the line is fetched here, /// at hover time, from whichever text the span is actually valid against. +/// A closed file is read by the caller's `disk_view` memo instead — one read +/// per hover — so this function never touches the disk. /// /// `None` — no snippet, today's card unchanged — wherever the two could -/// disagree: an unreadable file, a span the text does not cover, or a span -/// covering something other than the name that was hovered. A hover that -/// prints the wrong line is worse than one that prints none. +/// disagree: the span the live buffer does not cover, or a span covering +/// something other than the name that was hovered. A hover that prints the +/// wrong line is worse than one that prints none. fn declaration_snippet(ws: &Workspace, def: &Def, name: &str) -> Option { + // The file is open, so the index's span is against its *last saved* + // text and an unsaved edit above the declaration has already moved it. + // Find the same declaration logically instead, exactly as `nav.rs` + // does, and read the live buffer at the live span. let path = ws.index().path(def.file)?; - match ws.document_for_path(path) { - // The file is open, so the index's span is against its *last saved* - // text and an unsaved edit above the declaration has already moved it. - // Find the same declaration logically instead, exactly as `nav.rs` - // does, and read the live buffer at the live span. - Some(target) => { - let symbol = live_symbol(ws, target, def, name)?; - if !spells_exactly(&target.text, symbol.name_span, name) { - return None; - } - fenced(target.positions().whole_lines(symbol.decl_span)) - } - // Not open: disk text is what the index was built from, so the - // recorded span is the one to trust. - None => { - let text = ws.text_of(path)?; - if !spells_exactly(&text, def.name_span, name) { - return None; - } - let index = LineIndex::new(&text); - fenced(Positions::new(&text, &index).whole_lines(def.name_span)) - } + let target = ws.document_for_path(path)?; + let symbol = live_symbol(ws, target, def, name)?; + if !spells_exactly(&target.text, symbol.name_span, name) { + return None; } + fenced_sections( + &target.text, + &target.line_index, + symbol.decl_span, + symbol.detail_span.or(def.detail_span), + ) +} + +/// One closed file, read once per hover: the memo `symbol_hover` keys the +/// heading line and the snippet off, so a card never pays for the same file +/// twice. `None` for an unreadable file, which the caller renders as a bare +/// heading — exactly the card it always showed. +fn disk_view<'a>( + ws: &Workspace, + path: &std::path::Path, + memo: &'a mut Option<(std::path::PathBuf, String, LineIndex)>, +) -> Option<(&'a str, &'a LineIndex)> { + if !memo.as_ref().is_some_and(|held| held.0 == path) { + let text = ws.text_of(path)?; + let index = LineIndex::new(&text); + *memo = Some((path.to_path_buf(), text, index)); + } + memo.as_ref().map(|(_, text, index)| (text.as_str(), index)) } /// The live symbol in an open buffer that *is* this indexed declaration. +/// +/// Only the declarations spelling `name` are probed — `indexed_def_for_symbol` +/// is two index lookups per candidate, and every other symbol in the buffer +/// was going to fail the name test anyway. `symbols_named` hands them over in +/// declaration order, so the first-match tie-break between two live +/// declarations of one name is the one the old whole-buffer scan made. fn live_symbol<'a>( ws: &Workspace, target: &'a Document, def: &Def, name: &str, ) -> Option<&'a Symbol> { - target.semantics.symbols().iter().find(|symbol| { - symbol.name == name && indexed_def_for_symbol(ws, target, symbol) == Some(def) - }) + target + .semantics + .symbols_named(name) + .filter_map(|id| target.semantics.symbol(id)) + .find(|symbol| indexed_def_for_symbol(ws, target, symbol) == Some(def)) } /// The text a span covers, or `None` when the span is not inside `text` on @@ -708,6 +889,254 @@ mod tests { ); } + // ------------------------------------------------------------------ + // non-ANSI split ports: two sections, each with its comment + // ------------------------------------------------------------------ + + const SPLIT: &str = "\ +module alu ( + // the operand + data_in, + result // the result +); + +input signed [31:0] data_in; // 32-bit operand A +output reg [63:0] result; +endmodule +"; + + #[test] + fn a_split_port_hovers_as_two_sections_with_their_comments() { + // The same card from both places the port is declared: the header + // name and the body declaration. + let (ws, uri) = document(SPLIT); + for needle in ["data_in,", "data_in;"] { + let body = text_of(&hover(&ws, &uri, at(SPLIT, needle)).expect("hover")); + assert!(body.contains("**port** `data_in`"), "the heading: {needle:?} -> {body}"); + // Section one: the header, with the comment-only line above it. + assert!( + body.contains("```systemverilog\n // the operand\n data_in,\n```"), + "the header section, comment attached: {needle:?} -> {body}" + ); + // Section two: the body declaration, with its same-line comment. + assert!( + body.contains( + "```systemverilog\ninput signed [31:0] data_in; // 32-bit operand A\n```" + ), + "the detail section, comment included: {needle:?} -> {body}" + ); + // Two sections, not one merged block: two fences for one card. + assert!( + body.matches("```systemverilog").count() >= 2, + "two fenced sections: {needle:?} -> {body}" + ); + } + } + + #[test] + fn a_comments_below_a_declaration_attach_only_when_no_port_follows_them() { + // Below-comments attach when only the closer follows them (nothing + // else could they document)… + let below = "module alu (data_in);\ninput [7:0] data_in;\n// the operand\nendmodule\n"; + let (ws, uri) = document(below); + let body = text_of(&hover(&ws, &uri, at(below, "data_in;")).expect("hover")); + assert!( + body.contains("input [7:0] data_in;\n// the operand"), + "a comment under the last declaration is attached: got {body}" + ); + + // …but a comment block sitting just above the *next* port's + // declaration is that port's leading comment, not this one's. + let stolen = "module alu (data_in, result);\ninput [7:0] data_in;\n// about result\noutput result;\nendmodule\n"; + let (ws, uri) = document(stolen); + let body = text_of(&hover(&ws, &uri, at(stolen, "data_in,")).expect("hover")); + assert!( + !body.contains("// about result"), + "the next port's leading comment is not stolen: got {body}" + ); + // …and it does reach the port it documents. + let body = text_of(&hover(&ws, &uri, at(stolen, "result;") + 1).expect("hover")); + assert!(body.contains("// about result"), "attached to its own port: got {body}"); + } + + #[test] + fn an_old_style_task_argument_hovers_as_two_sections_too() { + // QA, PDS-3: a task or function argument named in the header and + // finished in the body is the same split shape a module port is, and + // now gets the same two-section card. + let text = "\ +module m; + // the operand + task t(a); + input [7:0] a; // 8 bits wide + $display(a); + endtask +endmodule +"; + let (ws, uri) = document(text); + for needle in ["a);", "a; //"] { + let body = text_of(&hover(&ws, &uri, at(text, needle)).expect("hover")); + assert!( + body.contains("```systemverilog\n // the operand\n task t(a);\n```"), + "the header section: {needle:?} -> {body}" + ); + assert!( + body.contains("```systemverilog\n input [7:0] a; // 8 bits wide\n```"), + "the body declaration's section: {needle:?} -> {body}" + ); + } + } + + #[test] + fn a_wrapped_next_declaration_keeps_its_own_leading_comment() { + // QA, PDS-1: the guard used to ask whether the line after a + // below-comment carried an identifier the port grammar could not + // account for. A declaration that *wraps*, with its direction keyword + // alone on the first line, carries no such identifier there — so the + // guard read "no other port here" and handed `result`'s comment to + // `data_in`. Only a line positively recognised as a closer may let a + // comment through now. + let wrapped = "\ +module alu (data_in, result); +input [7:0] data_in; +// about result +input + [7:0] result; +endmodule +"; + let (ws, uri) = document(wrapped); + let body = text_of(&hover(&ws, &uri, at(wrapped, "data_in;")).expect("hover")); + assert!( + !body.contains("// about result"), + "a wrapped next declaration's comment is not stolen: got {body}" + ); + // …and it reaches the port it was written for, above its own lines. + let body = text_of(&hover(&ws, &uri, at(wrapped, "result;")).expect("hover")); + assert!( + body.contains("// about result\ninput\n [7:0] result;"), + "attached above the wrapped declaration it documents: got {body}" + ); + } + + #[test] + fn a_wrapped_declaration_keeps_the_comment_below_it() { + // The other half of PDS-1: a wrapped declaration that really is the + // last one still takes the comment under it, because what follows the + // comment is a closer. + let text = "\ +module alu (data_in); +input + [7:0] data_in; +// the operand +endmodule +"; + let (ws, uri) = document(text); + let body = text_of(&hover(&ws, &uri, at(text, "data_in;")).expect("hover")); + assert!( + body.contains("input\n [7:0] data_in;\n// the operand"), + "the last, wrapped declaration takes the comment below it: got {body}" + ); + } + + #[test] + fn a_declaration_shows_the_comments_above_beside_and_below_it_at_once() { + // The owner's rule reads the three sources independently: same line, + // above, below. QA, PDS-2 — the implementation used to run a priority + // chain, so an above-comment or a trailing one silently suppressed + // the block below even when nothing else could claim it. + let text = "\ +module alu (data_in); +// above +input [7:0] data_in; // beside +// below +endmodule +"; + let (ws, uri) = document(text); + let body = text_of(&hover(&ws, &uri, at(text, "data_in;")).expect("hover")); + assert!( + body.contains("// above\ninput [7:0] data_in; // beside\n// below"), + "all three comments, in source order: got {body}" + ); + } + + #[test] + fn a_header_port_shows_the_comments_above_and_below_it_at_once() { + // PDS-2's own repros, both in one header: an above-comment (repro 1) + // and a same-line trailing comment (repro 2) each used to suppress + // the block below, which only `);` follows. + let text = "\ +module alu ( + // above + data_in, // beside + // below + result +); +input [7:0] data_in; +input result; +endmodule +"; + let (ws, uri) = document(text); + let body = text_of(&hover(&ws, &uri, at(text, "data_in,")).expect("hover")); + // `result` follows the block, so it is `result`'s comment, not this + // port's — the guard stays exactly as strict as it was. + assert!(!body.contains("// below"), "another port's comment is not stolen: got {body}"); + assert!( + body.contains(" // above\n data_in, // beside"), + "above and beside both attach: got {body}" + ); + + // With nothing but the closer after it, the same block does attach. + let last = "\ +module alu ( + // above + data_in // beside + // below +); +input [7:0] data_in; +endmodule +"; + let (ws, uri) = document(last); + let body = text_of(&hover(&ws, &uri, at(last, "data_in ")).expect("hover")); + assert!( + body.contains(" // above\n data_in // beside\n // below"), + "all three attach when only the closer follows: got {body}" + ); + } + + #[test] + fn the_line_above_a_header_port_does_not_leak_its_trailing_comment() { + // `result, // the result` above `data_in`'s own line: the line above + // carries another port, so its trailing comment stays result's. + let text = "\ +module alu ( + result, // the result + data_in +); +input [7:0] data_in; +endmodule +"; + let (ws, uri) = document(text); + let body = text_of(&hover(&ws, &uri, at(text, "data_in\n")).expect("hover")); + assert!(!body.contains("the result"), "not the port above's comment: got {body}"); + } + + #[test] + fn a_cross_file_split_port_shows_both_sections() { + let sub = "module sub (\n addr,\n ready\n);\ninput logic [15:0] addr;\noutput ready;\nendmodule\n"; + let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n"; + let (dir, ws, uri) = included("splitx", &[("sub.sv", sub), ("top.sv", top)]); + let body = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover")); + assert!( + body.contains("```systemverilog\n addr,\n```"), + "the header section, from the index's spans: got {body}" + ); + assert!( + body.contains("```systemverilog\ninput logic [15:0] addr;\n```"), + "the detail section, from the index's detail span: got {body}" + ); + let _ = fs::remove_dir_all(&dir); + } + #[test] fn hovering_a_declaration_shows_its_own_info() { let text = "module top;\n wire a;\nendmodule\n"; @@ -1142,18 +1571,15 @@ mod qa_hover_declarations { let _ = fs::remove_dir_all(&dir); } - /// Angle 2 (CRLF): a multi-line snippet from a CRLF file keeps the `\r` - /// on every line except the last, where `cut_to_size`'s `trim_end` - /// strips it. `local_text` (the in-file branch) has the same property — - /// this is not new to this round, but it is real: the fenced block for a - /// module header spanning multiple CRLF lines carries an embedded `\r` - /// before an interior `\n`. Cosmetic (most renderers show a fenced block - /// verbatim, so a stray `\r` is invisible or a non-issue in practice), - /// not a correctness break — filed as a low-severity finding rather than - /// a masked-corruption risk, since the text shown is still exactly the - /// bytes on disk. + /// Angle 2 (CRLF): a multi-line snippet from a CRLF file used to keep the + /// `\r` on every line except the last, where `cut_to_size`'s `trim_end` + /// stripped it — an embedded control character in the middle of a fenced + /// block. QA filed it (hover-declarations finding 2, port-detail-spans + /// PDS-4); `attached_lines` now strips the carriage return as it composes + /// each line, so the fence holds `\n`-separated lines whatever the file's + /// line endings are. Display text only: nothing writes to the buffer. #[test] - fn a_crlf_multiline_snippet_keeps_interior_carriage_returns() { + fn a_crlf_multiline_snippet_carries_no_carriage_returns() { // `wide`'s `decl_span` is its whole body (a module, like `PORTS` in // the dev's own tests), so its live-path snippet spans several CRLF // lines and is exactly where an interior, un-trimmed `\r` would show. @@ -1172,9 +1598,10 @@ mod qa_hover_declarations { let body = text_of(&hover(&ws, &uri, at(top, "wide u")).expect("hover")); assert!(body.contains("module wide ("), "got {body:?}"); + assert!(!body.contains('\r'), "no carriage return survives into the card: got {body:?}"); assert!( - body.contains("wire w0;\r\n"), - "an interior CRLF line keeps its \\r inside the fence: got {body:?}" + body.contains("module wide (\n input logic a\n);\n wire w0;"), + "the lines read as written, joined with plain newlines: got {body:?}" ); let _ = fs::remove_dir_all(&dir); } @@ -1311,18 +1738,17 @@ mod qa_hover_declarations { } /// Angle 7 (perf smell): a hover resolving into a large *closed* file - /// reads the whole file from disk and builds a fresh `LineIndex` over it - /// — twice, once inside `locate::line_number` for the heading and once - /// inside `declaration_snippet` for the snippet, since neither shares the - /// other's read. Not a correctness bug (hover is a rare, single-shot - /// request, and `text_of`/`LineIndex::new` are linear), but a measurable, - /// avoidable doubling of I/O and scan work on every disk-path hover. - /// Ignored by default (it writes/reads ~30 MB and just measures); run - /// with `cargo test --release -p lucisv_server large_closed -- --ignored - /// --nocapture` to see the number. + /// reads the whole file from disk and builds a fresh `LineIndex` over it. + /// Before the per-hover `disk_view` memo this happened **twice** — once + /// inside `locate::line_number` for the heading and once for the snippet — + /// and the memo's whole reason to exist is that it is now once. Not a + /// correctness assertion, just the number; run with `cargo test --release + /// -p lucisv_server large_closed -- --ignored --nocapture` to see it. The + /// same read, measured against the hover it serves, is in + /// `perf::hovering_across_files_into_a_closed_file`. #[test] #[ignore = "perf measurement, not a correctness assertion — see QA log"] - fn hovering_into_a_large_closed_file_reads_it_twice() { + fn hovering_into_a_large_closed_file_reads_it_once() { let dir = temp_dir("bigfile"); let mut sub = String::from("module sub (\n input logic [7:0] addr\n);\n"); for n in 0..600_000 { @@ -1351,7 +1777,7 @@ mod qa_hover_declarations { let elapsed = start.elapsed(); assert!(body.contains("[7:0] addr"), "got {body}"); eprintln!( - "hover into a {:.1} MB closed file took {:?} (reads the file + builds a LineIndex twice)", + "hover into a {:.1} MB closed file took {:?} (one read + one LineIndex, shared by heading and snippet)", sub.len() as f64 / 1_000_000.0, elapsed ); diff --git a/crates/lucisv_server/src/locate.rs b/crates/lucisv_server/src/locate.rs index 32d80aa..16d8332 100644 --- a/crates/lucisv_server/src/locate.rs +++ b/crates/lucisv_server/src/locate.rs @@ -25,7 +25,15 @@ pub fn location(ws: &Workspace, path: &Path, span: TextRange) -> Option Option { + if let Some(doc) = ws.document_for_path(path) { + return Some(doc.line_index.line_col(offset).0); + } let text = ws.text_of(path)?; Some(LineIndex::new(&text).line_col(offset).0) } diff --git a/crates/lucisv_server/src/nav.rs b/crates/lucisv_server/src/nav.rs index b3b2b04..f1dab56 100644 --- a/crates/lucisv_server/src/nav.rs +++ b/crates/lucisv_server/src/nav.rs @@ -31,7 +31,19 @@ pub fn definition(ws: &Workspace, uri: &Uri, offset: u32) -> Vec { } match path_to_uri_or_self(ws, uri) { Some(target) => { - vec![Location { uri: target, range: doc.positions().range(symbol.name_span) }] + let positions = doc.positions(); + // A non-ANSI port's *complete* declaration is the body + // `input wire clk;`, so that is where a jump lands first — + // the header name it jumped from stays second, exactly the + // two sections its hover card shows. + let mut locations = Vec::with_capacity(2); + if let Some(detail) = symbol.detail_span.filter(|span| !span.is_empty()) { + locations + .push(Location { uri: target.clone(), range: positions.range(detail) }); + } + locations + .push(Location { uri: target, range: positions.range(symbol.name_span) }); + locations } None => Vec::new(), } @@ -227,11 +239,15 @@ fn indexed_references( let span = ws .document_for_path(&target.declaration_path) .and_then(|doc| { - doc.semantics.symbols().iter().find_map(|symbol| { - (symbol.name == target.name - && indexed_def_for_symbol(ws, doc, symbol) == Some(&target.def)) - .then_some(symbol.name_span) - }) + // Same name-keyed lookup `hover.rs::live_symbol` makes, for + // the same reason: only same-named declarations can be this + // one, and the order they come in is declaration order either + // way, so the first match is unchanged. + doc.semantics + .symbols_named(&target.name) + .filter_map(|id| doc.semantics.symbol(id)) + .find(|symbol| indexed_def_for_symbol(ws, doc, symbol) == Some(&target.def)) + .map(|symbol| symbol.name_span) }) .unwrap_or(target.declaration_span); found.push((target.declaration_path, span));