Files
lucisv/crates/lucisv_server/src/hover/qa_hover_declarations.rs
T
Guoliang ChenandClaude Mythos 5.2 aa2259bfe1 Round 12: pure-move splits and hygiene
Splits resolve.rs, parser/item.rs, parser/instance.rs, format/stmt.rs and
lexer.rs (really 771 lines); moves 23 inline test modules of lucisv_server
to their own files; reasons on all 12 bare #[ignore]; the giant-line
references test times the real request; sites.py default root.
Output over 4,046 OpenTitan files byte-identical to a479faf.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
2026-11-26 20:39:56 -08:00

341 lines
17 KiB
Rust

// Author: Guoliang Chen, a Senior Digital Design Engineer
use super::*;
use crate::uri::path_to_uri;
use std::fs;
use std::path::PathBuf;
// Its one user is the case-insensitive-filesystem test below.
#[cfg(any(target_os = "macos", target_os = "windows"))]
use std::str::FromStr;
fn temp_dir(tag: &str) -> PathBuf {
let dir =
std::env::temp_dir().join(format!("lucisv_qa_hoverdecl_{tag}_{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).expect("temp dir");
dir
}
/// Angle 1: the disk-path guard slices `def.name_span` — a *fixed-length*
/// byte range, the old name's length, taken when the index was built —
/// and compares it for equality with the hovered name. It never checks
/// what comes immediately *after* that range. So an edit that extends the
/// declared identifier by appending characters (no reindex yet) leaves
/// the first `name.len()` bytes at the old offset still spelling the old
/// name — the guard passes — while the *actual* identifier at that
/// position is now a different, longer one that the file no longer
/// declares under the hovered name at all.
///
/// This is exactly the "same name at the stale span by coincidence"
/// attack the QA charter asks for, and it succeeds: the card claims to
/// show `addr`'s declaration and instead shows `addr2`'s, with no
/// indication anything is wrong. FINDING (see QA log, MEDIUM): the guard
/// needs a word-boundary check, not just a fixed-length substring match.
#[test]
fn a_disk_edit_that_only_appends_to_the_name_defeats_the_guard() {
let saved = "module sub (\n input logic [7:0] addr\n);\nendmodule\n";
let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n";
let (dir, ws, uri) = included("guardappend", &[("sub.sv", saved), ("top.sv", top)]);
// Same bytes up to and including "addr", then more identifier
// characters glued directly on — the stale span still lines up with
// "addr" as a prefix of the new, longer name.
let corrupted = "module sub (\n input logic [7:0] addr2\n);\nendmodule\n";
let prefix_len = saved.find("addr").unwrap() + 4;
assert_eq!(
&corrupted[..prefix_len],
&saved[..prefix_len],
"the attack requires the stale span to still land on the same bytes"
);
fs::write(dir.join("sub.sv"), corrupted).expect("rewrite");
let body = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover"));
let shows_wrong_declaration = body.contains("addr2");
if shows_wrong_declaration {
panic!(
"GUARD DEFEATED: the card for `.addr(...)` shows `addr2`'s line, \
not `addr`'s (which no longer exists) — got {body:?}"
);
}
}
fn included(tag: &str, files: &[(&str, &str)]) -> (PathBuf, Workspace, Uri) {
let dir = temp_dir(tag);
for (name, text) in files {
fs::write(dir.join(name), text).expect("write");
}
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![dir.clone()]);
let top = dir.join("top.sv");
let uri = path_to_uri(&top).expect("uri");
ws.set_document(uri.clone(), fs::read_to_string(&top).expect("read"));
(dir, ws, uri)
}
fn at(text: &str, needle: &str) -> u32 {
text.find(needle).expect("needle present") as u32
}
fn text_of(hover: &Hover) -> String {
match &hover.contents {
HoverContents::Markup(m) => m.value.clone(),
other => panic!("expected markup, got {other:?}"),
}
}
/// Angle 3: two live declarations of the same port name in an open
/// buffer (a transient state while editing — e.g. mid-refactor before the
/// stale one is deleted). The index still has one persisted `Def` for the
/// name, so `indexed_def_for_symbol` maps *either* live symbol back to
/// it, and `live_symbol`'s `.find()` picks whichever comes first in
/// `Semantics::symbols()` order.
///
/// Not a wrong-line *lie* — the guard still requires the chosen symbol's
/// own text to spell the name, which it always does by construction — but
/// it is a silent, arbitrary choice between two candidates with no signal
/// to the user that the buffer is ambiguous. This is inherited from
/// `nav.rs`'s pre-existing matcher (unchanged by this round: "one
/// matcher, so hover and go-to-definition can never disagree"), so it is
/// filed as an accepted pre-existing limitation, not a new defect. Pinned
/// here so a future change to the matcher's tie-break is not silent.
#[test]
fn duplicate_live_declarations_of_one_name_pick_the_first_one_silently() {
let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n";
let saved = "module sub (\n input logic [7:0] addr\n);\nendmodule\n";
let (dir, mut ws, uri) = included("dupdup", &[("sub.sv", saved), ("top.sv", top)]);
let sub_uri = path_to_uri(&dir.join("sub.sv")).expect("uri");
// Two ports named `addr`, different widths, in the same scope/kind.
let edited =
"module sub (\n input logic [7:0] addr,\n input logic [15:0] addr\n);\nendmodule\n";
ws.set_document(sub_uri, edited.to_string());
let body = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover"));
// Exactly one of the two widths appears — never both, never neither —
// confirming the pick is total but not both fenced blocks are shown.
let has_first = body.contains("[7:0] addr");
let has_second = body.contains("[15:0] addr");
assert!(has_first ^ has_second, "expected exactly one candidate shown: got {body}");
let _ = fs::remove_dir_all(&dir);
}
/// Angle 2 (CRLF): a multi-line snippet from a CRLF file used to keep the
/// `\r` on every line except the last, where `cut_to_size`'s `trim_end`
/// stripped it — an embedded control character in the middle of a fenced
/// block. QA filed it (hover-declarations finding 2, port-detail-spans
/// PDS-4); `attached_lines` now strips the carriage return as it composes
/// each line, so the fence holds `\n`-separated lines whatever the file's
/// line endings are. Display text only: nothing writes to the buffer.
#[test]
fn a_crlf_multiline_snippet_carries_no_carriage_returns() {
// `wide`'s `decl_span` is its whole body (a module, like `PORTS` in
// the dev's own tests), so its live-path snippet spans several CRLF
// lines and is exactly where an interior, un-trimmed `\r` would show.
// Both modules must exist at the *initial* index build — rewriting a
// module name into a file after `open_whole_workspace` without
// reindexing leaves the index not knowing that name, which is a
// workspace-setup mistake, not something this test is probing.
let wide =
"module wide (\r\n input logic a\r\n);\r\n wire w0;\r\n wire w1;\r\nendmodule\r\n";
let top = "module top;\r\n wide u ();\r\nendmodule\r\n";
let (dir, mut ws, uri) = included("crlfdecl", &[("wide.sv", wide), ("top.sv", top)]);
let wide_uri = path_to_uri(&dir.join("wide.sv")).expect("uri");
// Open the target so the live path (which widens `decl_span`, the
// multi-line span) is exercised rather than the disk path.
ws.set_document(wide_uri, wide.to_string());
let body = text_of(&hover(&ws, &uri, at(top, "wide u")).expect("hover"));
assert!(body.contains("module wide ("), "got {body:?}");
assert!(!body.contains('\r'), "no carriage return survives into the card: got {body:?}");
assert!(
body.contains("module wide (\n input logic a\n);\n wire w0;"),
"the lines read as written, joined with plain newlines: got {body:?}"
);
let _ = fs::remove_dir_all(&dir);
}
/// Angle 2: multi-byte UTF-8 content earlier in the same file (and on the
/// same line, before the declaration) must not panic `span_text` or
/// `whole_lines`. Both are `.get()`-based, so this is a belt-and-braces
/// regression pin rather than a discovered defect.
#[test]
fn multibyte_utf8_before_the_declaration_does_not_panic() {
// The identifier itself must stay ASCII (SV identifiers are), but the
// comment above it — which the widened whole-line span never reaches,
// yet whose byte length shifts every offset after it — is not.
let sub = "// 世界 comment — üñïçødé\nmodule sub (\n input logic [7:0] addr\n);\nendmodule\n";
let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n";
let (dir, ws, uri) = included("utf8decl", &[("sub.sv", sub), ("top.sv", top)]);
let body = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover"));
assert!(body.contains("input logic [7:0] addr"), "got {body}");
assert!(!body.contains("世界"), "only the declaration's own line: got {body}");
let _ = fs::remove_dir_all(&dir);
}
/// Angle 4: exactly `SNIPPET_LINES` lines is not cut (no note, no
/// ellipsis); one more line is.
#[test]
fn exactly_the_line_cap_is_not_cut_one_more_is() {
let mut sub = String::from("module sub (\n input logic [7:0] addr\n);\n");
// decl_span (module header .. matching paren, widened to whole lines)
// needs to land at exactly SNIPPET_LINES lines for the boundary case;
// instead, directly probe `cut_to_size`, which is what actually owns
// the boundary and is unit-testable without fighting the parser's
// span shape.
let _ = &mut sub;
let five = "a\nb\nc\nd\ne";
let (text, note) = cut_to_size(five);
assert_eq!(text, "a\nb\nc\nd\ne", "5 lines, unmodified: got {text:?}");
assert!(note.is_none(), "no note at exactly the cap: got {note:?}");
let six = "a\nb\nc\nd\ne\nf";
let (text6, note6) = cut_to_size(six);
assert_eq!(text6, "a\nb\nc\nd\ne …", "the first 5 lines, `f` dropped: got {text6:?}");
assert_eq!(note6, Some("*shown to 5 lines*".to_string()));
}
/// Angle 4: exactly `SNIPPET_CHARS` characters is not cut; one more is,
/// and the cut always lands on a character boundary even when the
/// boundary character is multi-byte.
#[test]
fn exactly_the_char_cap_is_not_cut_one_more_is_and_boundary_is_safe() {
let exact = "a".repeat(SNIPPET_CHARS);
let (text, note) = cut_to_size(&exact);
assert_eq!(text.chars().count(), SNIPPET_CHARS);
assert!(note.is_none(), "no note at exactly the cap: got {note:?}");
let over = "a".repeat(SNIPPET_CHARS + 1);
let (text2, note2) = cut_to_size(&over);
assert_eq!(text2, format!("{} …", "a".repeat(SNIPPET_CHARS)));
assert!(note2.is_some());
// The 400th character itself is multi-byte (3-byte '世'); char-based
// cutting must not split it and must not panic.
let mut mixed = "a".repeat(SNIPPET_CHARS - 1);
mixed.push('世');
mixed.push_str("bbbb");
let (text3, note3) = cut_to_size(&mixed);
// 400 kept chars (399 `a`s + the whole `世`, never half of it) plus the
// 2-char " …" suffix — the boundary character survives intact.
assert_eq!(text3.chars().count(), SNIPPET_CHARS + 2, "got {text3:?}");
assert!(text3.ends_with("世 …"), "the multi-byte char is not split: got {text3:?}");
assert!(note3.is_some());
}
/// Angle 2: the declared name sits at the very start of the file (offset
/// 0), with no character before it — `whole_lines`/`span_text` must not
/// underflow or panic.
#[test]
fn a_declaration_at_the_very_start_of_the_file_is_shown() {
let sub = "sub_pkg_marker foo;\nmodule sub (input logic clk);\nendmodule\n";
// `foo` at offset 0 is not itself a declaration hover's target here;
// instead exercise the disk path with `def.name_span.start == 0` by
// hovering a module whose file begins with the keyword `module`.
let sub2 = "module sub (input logic clk);\nendmodule\n";
let top = "module top;\n sub u (.clk(1'b0));\nendmodule\n";
let (dir, ws, uri) = included("startdecl", &[("sub.sv", sub2), ("top.sv", top)]);
let body = text_of(&hover(&ws, &uri, at(top, "sub u")).expect("hover"));
assert!(body.contains("```systemverilog\nmodule sub"), "got {body}");
let _ = fs::remove_dir_all(&dir);
let _ = sub;
}
/// Angle 2: the declaration is on the last line of the file, which has no
/// trailing newline. `whole_lines`'s `line_range(last).end` must resolve
/// to the true end of text, not run past it or leave a dangling range.
#[test]
fn a_declaration_on_the_last_line_with_no_trailing_newline_is_shown() {
let sub = "module sub (input logic clk);\nendmodule"; // no trailing \n
let top = "module top;\n sub u (.clk(1'b0));\nendmodule\n";
let (dir, ws, uri) = included("notrailingnl", &[("sub.sv", sub), ("top.sv", top)]);
let body = text_of(&hover(&ws, &uri, at(top, "sub u")).expect("hover"));
assert!(body.contains("```systemverilog\nmodule sub"), "got {body}");
let _ = fs::remove_dir_all(&dir);
}
/// Angle 3: the target file is open under a *different* `Uri` whose path
/// differs only in case from the index's recorded path (macOS/Windows
/// default to a case-insensitive filesystem, so this is the same file on
/// disk). `document_for_path` compares `PathBuf`s with `==`, which is
/// case-sensitive even on a case-insensitive filesystem, so the open
/// buffer is *not* found as "the target file open" and the code falls
/// back to the disk-read path. That fallback is exactly the safe
/// direction — it cannot show unsaved live edits, but it also cannot mix
/// up two differently-cased identities — so this is a documented
/// limitation, not a defect: an unsaved edit in a case-mismatched buffer
/// is invisible to hover until saved.
#[cfg(any(target_os = "macos", target_os = "windows"))]
#[test]
fn a_case_mismatched_open_buffer_is_not_recognized_as_the_target_falls_back_to_disk() {
let saved = "module sub (\n input logic [7:0] addr\n);\nendmodule\n";
let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n";
let (dir, mut ws, uri) = included("casefallback", &[("sub.sv", saved), ("top.sv", top)]);
// Open the same file via an upper-cased path.
let upper = dir.join("SUB.sv");
let upper_uri = Uri::from_str(&format!("file://{}", upper.display())).expect("uri");
let edited = "module sub (\n input logic [15:0] addr\n);\nendmodule\n";
ws.set_document(upper_uri, edited.to_string());
let body = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover"));
// Disk (saved) text wins, not the case-mismatched buffer's edit —
// confirms the fallback direction is the safe one.
assert!(body.contains("[7:0] addr"), "got {body}");
assert!(!body.contains("[15:0]"), "got {body}");
let _ = fs::remove_dir_all(&dir);
}
/// Angle 7 (perf smell): the **first** hover resolving into a large
/// *closed* file reads the whole file from disk and builds a fresh
/// `LineIndex` over it. It once did that twice — heading and snippet
/// independently — then once, through a per-hover memo, and since
/// `hover-line-index` (2026-08-28) it does it once *per file per
/// generation of that file*: the heading no longer wants any text at all
/// (`Def::lines`), and the snippet's read is held in
/// `Workspace::file_view` for the next hover. So this number is the first
/// touch, which is the one that still costs; the repeat is measured in
/// `perf::hovering_into_a_big_closed_file_first_touch_and_repeat`. Not a
/// correctness assertion, just the number; run with `cargo test --release
/// -p lucisv_server large_closed -- --ignored --nocapture` to see it.
#[test]
#[ignore = "perf measurement, not a correctness assertion — see QA log"]
fn hovering_into_a_large_closed_file_reads_it_once() {
let dir = temp_dir("bigfile");
let mut sub = String::from("module sub (\n input logic [7:0] addr\n);\n");
for n in 0..600_000 {
sub.push_str(&format!(" // filler line {n} of a big netlist-shaped file\n"));
}
sub.push_str("endmodule\n");
fs::write(dir.join("sub.sv"), &sub).expect("write");
let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n";
let top_path = dir.join("top.sv");
fs::write(&top_path, top).expect("write");
let mut ws = Workspace::default();
// The default `maxFileSize` is 1 MiB (`DEFAULT_MAX_FILE_SIZE`); a
// netlist-shaped file this size needs the cap raised or it is never
// indexed at all, which would make this measure nothing.
ws.set_client_settings(crate::settings::ClientSettings {
max_file_size: 100_000_000,
..Default::default()
});
ws.open_whole_workspace(vec![dir.clone()]);
let uri = path_to_uri(&top_path).expect("uri");
ws.set_document(uri.clone(), top.to_string());
let start = std::time::Instant::now();
let body = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover"));
let elapsed = start.elapsed();
assert!(body.contains("[7:0] addr"), "got {body}");
let start = std::time::Instant::now();
let _ = hover(&ws, &uri, at(top, "addr(8")).expect("hover");
let again = start.elapsed();
eprintln!(
"hover into a {:.1} MB closed file took {:?} the first time (one read + one \
LineIndex, for the snippet alone) and {:?} the second (nothing read)",
sub.len() as f64 / 1_000_000.0,
elapsed,
again
);
let _ = fs::remove_dir_all(&dir);
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com