diff --git a/TODO.md b/TODO.md index 26fce89..96e26c5 100644 --- a/TODO.md +++ b/TODO.md @@ -585,6 +585,19 @@ later: salsa question is ever reopened, that is the number it has to beat — incremental *lexing and parsing*, not incremental queries over a whole-file parse, and it lands squarely on `CLAUDE.md`'s hard invariants 1 and 2. + **A fourth piece answered without salsa, 2026-08-28** + (`docs/features/hover-line-index/README.md`): a derived fact a query used to + recompute — the *line* a declaration is written on, which cost a whole file + read and a whole `LineIndex` per request — is now computed once when the + file is indexed and stored beside the span (`Def::lines`, `FACTS_FORMAT` + 3 → 4), and the one thing still needing that file's text is served from a + small bounded cache of closed files. A repeat hover into a 12 MB closed file + goes 5.75 ms → 0.95 µs; a whole scan is unchanged and the store grows 2.9 %. + Still no query graph: what is cached is a value, invalidated at four named + points, not a node in a dependency graph. **The larger number the same round + measured is not an incrementality problem at all**: the first request of a + session waits out the startup scan (780 ms cold, 287 ms warm), because + `Server::new` scans before the message loop starts. Filed there, not fixed. - [x] **Release prep.** `LICENSE` (MIT), `CHANGELOG.md` (v0.2.0), version bumped to 0.2.0 across the workspace and the extension, `tools/release.sh` (release binaries + `.vsix` + `SHA256SUMS` into a gitignored `dist/`) and diff --git a/crates/lucisv_server/src/hover.rs b/crates/lucisv_server/src/hover.rs index ac605c3..eb24264 100644 --- a/crates/lucisv_server/src/hover.rs +++ b/crates/lucisv_server/src/hover.rs @@ -179,11 +179,6 @@ 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 path = ws.index().path(def.file).map(|p| p.to_path_buf()); @@ -192,28 +187,34 @@ fn symbol_hover(ws: &Workspace, doc: &Document, offset: u32) -> Option { 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. + // resolves the current span, and its guards stay. The + // line comes from that buffer's own index rather than + // from `def.lines`, because the buffer may hold + // unsaved edits the index has not seen. 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) + } else { + // The heading costs nothing: the line was recorded + // when the file was indexed, from the same text the + // span came from (`vlog_semantic::DeclLines`). Only + // the snippet still wants the file's text, and that + // comes from the workspace's shared view — one read + // per file per generation, so a card naming one file + // twice, and the next hover into it, are both free. + where_ = Some(format!("{}:{}", display_name(path), def.lines.name)); + snippet = name.zip(ws.file_view(path)).and_then(|(name, view)| { + spells_exactly(&view.text, def.name_span, name) .then(|| { - fenced_sections(text, index, def.name_span, def.detail_span) + fenced_sections( + &view.text, + &view.lines, + def.name_span, + def.detail_span, + ) }) .flatten() }); - } else { - where_ = Some(display_name(path)); } } let where_ = where_.unwrap_or_else(|| "the workspace".to_string()); @@ -385,11 +386,11 @@ const SNIPPET_CHARS: usize = 400; /// 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. +/// The index holds spans, kinds and lines but no text +/// (`docs/features/workspace-index/README.md`), so the *source* is fetched +/// here, at hover time, from whichever text the span is actually valid +/// against. A closed file is served by `Workspace::file_view` in the caller +/// instead, so this function never touches the disk. /// /// `None` — no snippet, today's card unchanged — wherever the two could /// disagree: the span the live buffer does not cover, or a span covering @@ -414,23 +415,6 @@ fn declaration_snippet(ws: &Workspace, def: &Def, name: &str) -> Option ) } -/// 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` @@ -1201,6 +1185,92 @@ endmodule let _ = fs::remove_dir_all(&dir); } + #[test] + fn a_closed_files_heading_line_comes_from_the_index_and_not_from_a_read() { + // The round's central claim: `file:line` for an indexed declaration is + // `Def::lines`, recorded when the file was scanned, so the heading + // costs no read at all. Proved by removing the file from under the + // index — a heading that still names the line cannot have read it. + let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n"; + let (dir, ws, uri) = included("headingfromindex", &[("sub.sv", PORTS), ("top.sv", top)]); + fs::remove_file(dir.join("sub.sv")).expect("remove"); + + let body = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover")); + assert!(body.contains("**port** — declared in `sub.sv:2`"), "got {body}"); + // The snippet is the half that really wanted the text, and it is + // dropped rather than guessed at — exactly as it always was for a + // file that cannot be read. + assert!(!body.contains("```systemverilog"), "no snippet without text: got {body}"); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn a_second_hover_into_one_closed_file_reads_nothing() { + // The other half: the snippet's read is shared through + // `Workspace::file_view`, so the file is read once and the next hover + // into it — the same card, or another name in the same file — is + // served from what that read left behind. Observed the only honest + // way: rewrite the file behind the server's back and require the + // second card to be the first one. Stale text can only ever *omit* a + // snippet (the `spells_exactly` guard), never show a wrong line. + let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n"; + let (dir, ws, uri) = included("viewshared", &[("sub.sv", PORTS), ("top.sv", top)]); + let first = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover")); + assert!(first.contains("input logic [7:0] addr"), "premise: got {first}"); + + fs::write(dir.join("sub.sv"), "module sub (\n input logic [15:0] addr\n);\nendmodule\n") + .expect("write"); + let second = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover")); + assert_eq!(second, first, "the second hover did not read the file again"); + let _ = fs::remove_dir_all(&dir); + } + + /// QA (2026-08-28): the staleness window the README's Assumptions section + /// claims — "a line is a fact about the same snapshot the span is... where + /// the file has changed on disk with nothing telling the server, both are + /// stale together" — reproduced rather than taken on faith, and in the + /// one shape that could actually disagree: the index was built from the + /// *original* `sub.sv`, but `sub.sv` is rewritten on disk — no `didSave`, + /// no watcher event, no `update_one`/`rebuild_index` call, so the index is + /// never told — **before the view cache ever reads it**, so the first + /// hover's disk read sees the *new* bytes under the *old* span and offset. + /// The heading must still show the line the index recorded at the last + /// scan (stale, not a fresh-read line the index never computed), and the + /// snippet, reading the genuinely current text, must find the old span no + /// longer spells `addr` there and drop itself via `spells_exactly` rather + /// than show whatever now sits at that byte range. + #[test] + fn an_unreindexed_disk_edit_leaves_a_stale_heading_and_no_wrong_snippet() { + let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n"; + let (dir, ws, uri) = included("staleheading", &[("sub.sv", PORTS), ("top.sv", top)]); + + // Edited behind the server's back, before any hover has read this + // file at all: four lines inserted above the module, so `addr`'s true + // line is now 6 — and the byte offset the index still holds for it + // (from the *original* `sub.sv`) now lands inside a comment, not + // `addr`. The view cache is empty for this path, so the hover below + // is a genuinely fresh disk read of the edited bytes. + fs::write( + dir.join("sub.sv"), + "// one\n// two\n// three\n// four\nmodule sub (\n input logic [7:0] addr,\n\ + \x20 output logic ready\n);\nendmodule\n", + ) + .expect("write"); + + let after = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover")); + assert!( + after.contains("**port** — declared in `sub.sv:2`"), + "the heading must show the line the index recorded, not the file's true current \ + line (6), until something reindexes it: got {after}" + ); + assert!( + !after.contains("```systemverilog"), + "the snippet must be dropped, not show the comment the stale span now lands on: \ + got {after}" + ); + let _ = fs::remove_dir_all(&dir); + } + #[test] fn a_package_member_shows_its_declaration_line() { let pkg = @@ -1737,15 +1807,18 @@ mod qa_hover_declarations { let _ = fs::remove_dir_all(&dir); } - /// Angle 7 (perf smell): a hover resolving into a large *closed* file - /// reads the whole file from disk and builds a fresh `LineIndex` over it. - /// 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 + /// 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. The - /// same read, measured against the hover it serves, is in - /// `perf::hovering_across_files_into_a_closed_file`. + /// -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() { @@ -1776,10 +1849,15 @@ mod qa_hover_declarations { 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 {:?} (one read + one LineIndex, shared by heading and snippet)", + "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 + elapsed, + again ); let _ = fs::remove_dir_all(&dir); } diff --git a/crates/lucisv_server/src/index_cache.rs b/crates/lucisv_server/src/index_cache.rs index b56d1b8..93db63b 100644 --- a/crates/lucisv_server/src/index_cache.rs +++ b/crates/lucisv_server/src/index_cache.rs @@ -569,27 +569,46 @@ mod tests { } #[test] - fn a_store_from_the_previous_facts_format_is_dropped_not_misread() { - // Simulates a store written by the released 0.12.1 (FACTS_FORMAT 2, - // before detail_span). Same CACHE_FORMAT and VERSION as today — only - // FACTS_FORMAT differs — so the only thing that can catch it is the - // FACTS_FORMAT field in the header line. QA finding for - // docs/features/port-detail-spans/README.md: the format bump 2 → 3 - // had no regression test of its own; this is that test. - let dir = TempDir::new("factsformat2"); + fn a_store_from_any_previous_facts_format_is_dropped_not_misread() { + // Every `FACTS_FORMAT` this build is not, with today's `CACHE_FORMAT` + // and `VERSION` — so the header's format field is the only thing that + // can catch them. Written as a loop rather than against one number so + // it cannot go stale the next time a record grows a field: it was + // pinned at 2 for the `detail_span` bump (QA finding, + // `docs/features/port-detail-spans/README.md`) and would have gone on + // testing 2 forever. + let dir = TempDir::new("factsformats"); let file = dir.file("m.sv", M); let encoded = facts(&file, M).encode().expect("encodes"); - let old_format_store = format!( - "lucisv-index-cache\t{CACHE_FORMAT}\t2\t{VERSION}\n{}\n", - line(content_hash(M.as_bytes()), &encoded) - ); - std::fs::write(dir.path.join(FILE), old_format_store).expect("write"); + for format in 1..FACTS_FORMAT { + let old_format_store = format!( + "lucisv-index-cache\t{CACHE_FORMAT}\t{format}\t{VERSION}\n{}\n", + line(content_hash(M.as_bytes()), &encoded) + ); + std::fs::write(dir.path.join(FILE), old_format_store).expect("write"); + let cache = IndexCache::open(Some(dir.path.clone())); + assert!( + cache.facts_for(&file, M).is_none(), + "a format-{format} record must not be read as a format-{FACTS_FORMAT} one" + ); + } - let mut cache = IndexCache::open(Some(dir.path.clone())); + // And the belt to that brace: a record really written in the previous + // format — this one is a format-3 record, which is today's minus the + // two per-declaration line fields `hover-line-index` added — does not + // decode as one of today's *even if* something served it past the + // header. Field-shifting is what the length prefixes and the + // end-of-record check exist to make impossible. + let format_3 = strip_the_line_fields(&encoded); + assert_ne!(format_3, encoded, "premise: the fixture has a declaration to strip"); assert!( - cache.facts_for(&file, M).is_none(), - "a format-2 record must not be read as a format-3 one" + FileFacts::decode(&format_3).is_none(), + "a format-3 record decoded as a format-4 one: {format_3}" ); + + // Finally, the store is replaced under this build's header rather than + // appended to, and reopening reads the fresh record back. + let mut cache = IndexCache::open(Some(dir.path.clone())); cache.record(&facts(&file, M), M); let text = dir.store_text(); assert!( @@ -602,6 +621,23 @@ mod tests { ); } + /// Today's encoded record, minus the two line fields every declaration + /// gained in `FACTS_FORMAT` 4 — i.e. what format 3 wrote for the same + /// file. `M` declares exactly one unit and no members, so the fields to + /// drop are the two immediately after that unit's four span offsets. + fn strip_the_line_fields(encoded: &str) -> String { + let mut fields: Vec<&str> = encoded.split('\t').collect(); + let Some(units) = fields.iter().position(|f| *f == "U") else { + return encoded.to_string(); + }; + // U, count, name, kind, name_span×2, detail×2, then the two lines. + let lines_at = units + 8; + if fields.len() > lines_at + 1 { + fields.drain(lines_at..lines_at + 2); + } + fields.join("\t") + } + #[test] fn an_empty_store_is_a_claim_to_finish_rather_than_a_store_to_replace() { // The one shape `create_new` introduces: a zero-byte store, left by a diff --git a/crates/lucisv_server/src/locate.rs b/crates/lucisv_server/src/locate.rs index 16d8332..7eefcc3 100644 --- a/crates/lucisv_server/src/locate.rs +++ b/crates/lucisv_server/src/locate.rs @@ -3,12 +3,15 @@ //! The workspace index deliberately keeps no file contents //! (`docs/features/workspace-index/README.md`), so a span in another file has //! to be converted against that file's text, fetched here with the same -//! open-buffer-beats-disk precedence the index rebuild uses. +//! open-buffer-beats-disk precedence the index rebuild uses — from the +//! buffer's own line index when there is one, and otherwise through +//! `Workspace::file_view`, which reads a closed file at most once per +//! generation of it rather than once per question about it. use std::path::Path; use lsp_types::Location; -use vlog_parser::{LineIndex, TextRange}; +use vlog_parser::TextRange; use crate::convert::Positions; use crate::state::Workspace; @@ -17,25 +20,28 @@ use crate::uri::path_to_uri; /// The location of a byte span inside a workspace file. pub fn location(ws: &Workspace, path: &Path, span: TextRange) -> Option { let uri = path_to_uri(path)?; - let text = ws.text_of(path)?; - let index = LineIndex::new(&text); - let range = Positions::new(&text, &index).range(span); - Some(Location { uri, range }) + if let Some(doc) = ws.document_for_path(path) { + return Some(Location { uri, range: doc.positions().range(span) }); + } + let view = ws.file_view(path)?; + Some(Location { uri, range: Positions::new(&view.text, &view.lines).range(span) }) } /// The 1-based line a byte offset falls on, for hover text that names a file /// and a line rather than jumping to it. /// /// An open buffer answers from the line index it already carries; a closed -/// file is read and indexed here — which is why a hover that names one file -/// twice reads it through the per-request memo in `hover::symbol_hover`, not -/// through two calls here. +/// file answers from the shared view cache. **An indexed declaration should +/// not come here at all** — `Def::lines` already holds its line, recorded when +/// the file was indexed, and that answer costs nothing +/// (`docs/features/hover-line-index/README.md`). What is left for this +/// function is the spans the index records no line for, which today is a +/// `` `define``'s. pub fn line_number(ws: &Workspace, path: &Path, offset: u32) -> 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) + Some(ws.file_view(path)?.lines.line_col(offset).0) } /// How a file is named in hover text: its file name, which is what a Verilog diff --git a/crates/lucisv_server/src/perf.rs b/crates/lucisv_server/src/perf.rs index 2cf6e31..a11ba90 100644 --- a/crates/lucisv_server/src/perf.rs +++ b/crates/lucisv_server/src/perf.rs @@ -252,10 +252,14 @@ fn hovering_a_local_declaration() { #[test] #[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"] fn hovering_across_files_into_a_closed_file() { - // The disk path: the target file is closed, so the card's heading line and - // its snippet both come out of one read (`hover::disk_view`). The second - // read that memo removed is measured beside it — it is the whole file - // again, plus a whole `LineIndex` again. + // The disk path: the target file is closed, so the card's heading line + // comes from the index (`Def::lines`, no read at all) and its snippet from + // the workspace's shared view of that file — read once, then held. This + // is a *mean of twenty*, so nineteen of the runs are the held case: it is + // the steady-state hover, not the first touch (which + // `hovering_into_a_big_closed_file_first_touch_and_repeat` reports on its + // own). Measured beside it is the read the first touch pays and every + // later one does not. for lines in SIZES { let sub = generated_module("sub", lines); let top = "module top;\n sub u (.data_in(32'h0));\nendmodule\n"; @@ -279,12 +283,73 @@ fn hovering_across_files_into_a_closed_file() { assert!(format!("{card:?}").contains("sub.sv"), "{card:?}"); eprintln!( "hover, closed cross-file target: {lines} lines took {took:?} \ - (one read + LineIndex of that file: {one_read:?}, which is what the memo saves)" + (one read + LineIndex of that file: {one_read:?}, which only the first touch pays)" ); let _ = std::fs::remove_dir_all(&dir); } } +/// `cargo test --release -p lucisv_server perf::hovering_into_a_big -- --ignored --nocapture --test-threads=1` +#[test] +#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"] +fn hovering_into_a_big_closed_file_first_touch_and_repeat() { + // The owner's report, measured: hovering an *instantiation* and hovering + // one of its *ports* into a closed file that is big — the netlist-adjacent + // shape a real workspace has one of. Two numbers per hover: the first + // touch of that file in the session, and the touch after it, which is the + // one a text cache can make free. + // + // "First touch" is cold to *this process* and to nothing else: the file + // was written moments ago, so the OS page cache still holds it and the + // read below is the cheap kind. A genuinely cold disk is worse than this, + // never better. + let sub = big_module("sub", 12_000_000); + let top = "module top;\n sub u (.data_in(32'h0));\nendmodule\n"; + let dir = scratch("bighover", &[("sub.sv", sub.as_str()), ("top.sv", top)]); + let uri = path_to_uri(&dir.join("top.sv")).expect("uri"); + let instantiation = top.find("sub u").expect("an instantiation") as u32; + let port = top.find("data_in(").expect("a port connection") as u32; + + for (what, offset) in [("instantiation", instantiation), ("port", port)] { + // A fresh workspace per measurement, so "first touch" really is one. + let mut ws = Workspace::default(); + ws.set_client_settings(crate::settings::ClientSettings { + max_file_size: 100_000_000, + ..Default::default() + }); + ws.open_whole_workspace(vec![dir.clone()]); + ws.set_document(uri.clone(), top.to_string()); + + let start = Instant::now(); + let card = hover(&ws, &uri, black_box(offset)).expect("a cross-file card"); + let first = start.elapsed(); + assert!(format!("{card:?}").contains("sub.sv"), "{card:?}"); + let repeat = mean(10, || { + black_box(hover(&ws, &uri, black_box(offset))); + }); + eprintln!( + "hover on a {what} into a {:.1} MB closed file: first touch {first:?}, \ + repeat {repeat:?}", + sub.len() as f64 / 1_000_000.0 + ); + } + let _ = std::fs::remove_dir_all(&dir); +} + +/// A module of at least `bytes` bytes: a small ANSI header — the declaration a +/// hover actually lands on — behind a wall of filler lines, which is the shape +/// of the files the owner's report is about. +fn big_module(name: &str, bytes: usize) -> String { + let mut src = format!("module {name} (\n input logic [31:0] data_in\n);\n"); + let mut n = 0; + while src.len() < bytes { + src.push_str(&format!(" // filler line {n} of a big netlist-shaped file\n")); + n += 1; + } + src.push_str("endmodule\n"); + src +} + /// `cargo test --release -p lucisv_server perf::reindexing -- --ignored --nocapture --test-threads=1` #[test] #[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"] diff --git a/crates/lucisv_server/src/state.rs b/crates/lucisv_server/src/state.rs index 383ac7d..c2be32d 100644 --- a/crates/lucisv_server/src/state.rs +++ b/crates/lucisv_server/src/state.rs @@ -3,9 +3,11 @@ //! `docs/features/lucisv-server/README.md`; the short version is that a buffer's //! analysis is rebuilt on every change and the index only on save. +use std::cell::RefCell; use std::collections::{HashMap, HashSet}; use std::fs; use std::path::{Path, PathBuf}; +use std::rc::Rc; use lsp_types::Uri; use vlog_parser::ast::SourceFile; @@ -32,6 +34,36 @@ use crate::uri::uri_to_path; /// query would read the whole workspace. pub const WORKSPACE_SYMBOL_LIMIT: usize = 256; +/// One **closed** workspace file's text and the line index over it, held by +/// [`Workspace`] just long enough that answering twice about the same file +/// reads it once. +/// +/// Only closed files: an open buffer's own `Document` is the authority on its +/// text, and caching a second copy of it would be a way for the two to +/// disagree. +pub struct FileView { + /// The file this view was read from. + pub path: PathBuf, + /// Its text, as it was on disk when the view was made. + pub text: String, + /// The line index over exactly that text. + pub lines: LineIndex, +} + +/// How many closed files the view cache holds, and how much text they may add +/// up to. +/// +/// Two bounds, because they answer two different questions. `MAX_VIEWS` is how +/// many files one answer can name — a hover card names one or two, a +/// references list walks a handful before it moves on — and four is a handful. +/// `MAX_VIEW_BYTES` is the memory question, and it exists because the file +/// this cache is *for* can be tens of megabytes on its own: without it, four +/// netlists would be half a gigabyte of server. The newest view is kept +/// whatever it weighs, so a single huge file simply evicts everything else +/// rather than refusing to be cached at all. +const MAX_VIEWS: usize = 4; +const MAX_VIEW_BYTES: usize = 8 * 1024 * 1024; + /// One open buffer, fully analyzed. Every field is derived from `text`, so a /// change throws the whole thing away and builds a new one. pub struct Document { @@ -151,7 +183,7 @@ impl Document { /// the analysis of the empty file, and such a buffer contributes nothing to /// the index at all (see `collect_sources`). pub fn facts(&self, path: PathBuf) -> FileFacts { - FileFacts::from_analysis(path, &self.tree, &self.defines, &self.semantics) + FileFacts::from_analysis(path, &self.tree, &self.defines, &self.semantics, &self.line_index) } /// The completion words this buffer contributes, read off the tokens it was @@ -309,6 +341,24 @@ fn oversize(path: &Path, cap: u64) -> Option { (size > cap).then_some(size) } +/// Cut the view cache back to its two bounds, newest first. +/// +/// The newest view is kept whatever it weighs: one netlist-shaped file can +/// exceed the whole byte budget on its own, and a cache that refused to hold +/// it would be useless for exactly the file it exists for. +fn trim_views(views: &mut Vec>) { + let mut bytes = 0usize; + let mut kept = 0usize; + for view in views.iter() { + bytes += view.text.len(); + if kept == MAX_VIEWS || (kept > 0 && bytes > MAX_VIEW_BYTES) { + break; + } + kept += 1; + } + views.truncate(kept); +} + /// Every open buffer plus the workspace index they are resolved against. #[derive(Default)] pub struct Workspace { @@ -338,6 +388,11 @@ pub struct Workspace { /// the currently-open buffers, so **closing a file never narrows the /// index** — see `docs/features/index-scope/README.md`. opened_dirs: Vec, + /// The last few closed files any answer needed the text of, newest first. + /// A cache and nothing else: every entry can be dropped at any moment + /// without changing an answer, and every way a file's text can move drops + /// its entry (see [`Workspace::file_view`]). + views: RefCell>>, } impl Workspace { @@ -607,6 +662,12 @@ impl Workspace { self.opened_dirs.sort(); } } + // This path now has a buffer speaking for it, so whatever the view + // cache holds for it is both unwanted and possibly older than the + // edits the buffer carries. + if let Some(path) = path.as_deref() { + self.forget_view(path); + } let doc = match self.is_large(&text) { true => Document::large(path, text), false => Document::new(path, text, &self.index), @@ -632,7 +693,12 @@ impl Workspace { } pub fn close_document(&mut self, uri: &Uri) { - self.docs.remove(uri); + let closed = self.docs.remove(uri); + // Disk is the authority again, and a view made before this buffer was + // opened predates every save it made. + if let Some(path) = closed.and_then(|doc| doc.path) { + self.forget_view(&path); + } } /// Every open buffer's URI, for republishing diagnostics after a rebuild. @@ -665,6 +731,9 @@ impl Workspace { /// reported: they cost a small fraction of the parse, and a bar that went /// to 100% and then sat there would be worse than one that ends. pub fn rebuild_index_with(&mut self, watch: &mut dyn FnMut(IndexEvent)) -> Vec { + // A rescan says nothing about *which* file moved, so nothing held from + // before it can be trusted. + self.views.borrow_mut().clear(); let mut scope = self.collect_sources(watch, HeldAnalyses::Wanted); let sources = std::mem::take(&mut scope.texts); let mut analyzed = std::mem::take(&mut scope.analyzed); @@ -759,6 +828,8 @@ impl Workspace { if !self.index.files().iter().any(|held| held == path) { return false; } + // Re-indexing one file *is* the claim that its bytes moved. + self.forget_view(path); match self.current_text(path) { Some(text) => { // The same rule a whole rebuild follows: when the text came @@ -941,6 +1012,65 @@ impl Workspace { Sources { texts, analyzed, incdirs: scope.incdirs, warnings: scope.warnings } } + /// One **closed** file's text and line index, read at most once per file + /// per generation of that file. + /// + /// `None` for a file that cannot be read, and — deliberately — for one an + /// open buffer speaks for: that buffer's `Document` already holds both, + /// and a second copy here would be a second opinion. Callers that want + /// "whichever text is authoritative" ask `document_for_path` first, as + /// `locate` does. + /// + /// **A cache, never a correctness input.** Every entry is dropped the + /// moment anything could have moved the file's text under it, and there + /// are exactly four such moments: + /// + /// * [`Workspace::set_document`] — a `didOpen`/`didChange`/`didSave` for + /// that path; the buffer becomes the authority and the disk copy is no + /// longer what a reader wants; + /// * [`Workspace::close_document`] — the buffer stops being the authority, + /// and whatever was cached for that path predates the edits it may have + /// saved; + /// * [`Workspace::update_one`] — one file re-indexed, which is exactly the + /// claim that its bytes changed; + /// * [`Workspace::rebuild_index_with`] — a whole rescan, which claims + /// nothing about *which* file moved, so the whole cache goes. + /// + /// What survives all four is a file changed on disk with nothing telling + /// this server so — and there the index's own spans are stale by the same + /// event, which is what `hover`'s `spells_exactly` guard exists for: a + /// stale view can only ever *omit* a snippet, never show a wrong line. + pub fn file_view(&self, path: &Path) -> Option> { + if self.document_for_path(path).is_some() { + return None; + } + if let Some(hit) = self.cached_view(path) { + return Some(hit); + } + let text = fs::read_to_string(path).ok()?; + let view = + Rc::new(FileView { path: path.to_path_buf(), lines: LineIndex::new(&text), text }); + let mut views = self.views.borrow_mut(); + views.insert(0, Rc::clone(&view)); + trim_views(&mut views); + Some(view) + } + + /// The held view for `path`, moved to the front so the bounds below drop + /// whatever has gone longest unused. + fn cached_view(&self, path: &Path) -> Option> { + let mut views = self.views.borrow_mut(); + let at = views.iter().position(|view| view.path == path)?; + views[..=at].rotate_right(1); + views.first().cloned() + } + + /// Drop whatever is held for one file. Called wherever that file's text + /// may have moved; see [`Workspace::file_view`] for the list. + fn forget_view(&mut self, path: &Path) { + self.views.borrow_mut().retain(|view| view.path != path); + } + /// The text of a workspace file: the open buffer if there is one, else /// what is on disk. Same precedence the index rebuild uses, so a location /// is never computed against text the index did not see. @@ -1340,6 +1470,228 @@ mod tests { } } + // ------------------------------------------------------------------ + // the closed-file view cache + // ------------------------------------------------------------------ + // + // Every test below observes the cache the only honest way there is: it + // changes a file on disk *without telling the server*, and asks whether + // the next view still shows the old text. A view that survives such an + // edit was cached; one that does not was re-read. That is a cache and not + // a correctness input, so "still shows the old text" is the expected + // answer everywhere the invalidation list does not name. + + /// A file with `n` declared modules, so its text is both readable and + /// tellable apart. + fn versioned(n: usize) -> String { + (0..n).map(|k| format!("module m{k};\nendmodule\n")).collect() + } + + #[test] + fn a_closed_files_text_is_read_once_and_then_reused() { + let tree = Tree::new("viewreuse"); + tree.write("sub.sv", &versioned(1)); + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![tree.path.clone()]); + let path = tree.path.join("sub.sv"); + + let first = ws.file_view(&path).expect("readable").text.clone(); + assert!(first.contains("m0"), "premise: the file was read"); + // Behind the server's back — no didSave, no watcher, no rescan. + tree.write("sub.sv", &versioned(2)); + assert_eq!( + ws.file_view(&path).expect("readable").text, + first, + "the second question about one file costs no second read" + ); + } + + #[test] + fn a_file_an_open_buffer_speaks_for_has_no_view_of_its_own() { + // The buffer's own `Document` is the authority on its text; a second + // copy here would be a second opinion, so there is deliberately none. + let tree = Tree::new("viewopen"); + tree.write("sub.sv", &versioned(1)); + let path = tree.path.join("sub.sv"); + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![tree.path.clone()]); + assert!(ws.file_view(&path).is_some(), "premise: readable while closed"); + + ws.set_document(uri(&format!("file://{}", path.display())), versioned(3)); + assert!(ws.file_view(&path).is_none(), "an open buffer answers for itself"); + } + + #[test] + fn every_way_a_files_text_can_move_drops_its_view() { + // The four invalidation points named in `Workspace::file_view`'s doc + // comment, each proved by the same experiment: warm the view, change + // the file on disk, run the event, and require the next view to be + // the new text rather than the held one. + let path_uri = |path: &Path| uri(&format!("file://{}", path.display())); + + for event in ["didOpen", "didClose", "update_one", "rebuild"] { + let tree = Tree::new(&format!("viewdrop_{event}")); + tree.write("sub.sv", &versioned(1)); + let path = tree.path.join("sub.sv"); + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![tree.path.clone()]); + + let held = ws.file_view(&path).expect("readable").text.clone(); + tree.write("sub.sv", &versioned(2)); + assert_eq!(ws.file_view(&path).expect("readable").text, held, "premise: {event}"); + + match event { + // Opening the file: the buffer takes over, and closing it + // again must not hand back the view from before the buffer + // existed — it predates every save that buffer made. + "didOpen" | "didClose" => { + ws.set_document(path_uri(&path), versioned(9)); + assert!(ws.file_view(&path).is_none(), "open: no view at all"); + ws.close_document(&path_uri(&path)); + } + "update_one" => { + assert!(ws.update_one(&path), "the index holds this file"); + } + "rebuild" => { + ws.rebuild_index(); + } + _ => unreachable!(), + } + let after = ws.file_view(&path).expect("readable").text.clone(); + assert_ne!(after, held, "{event} must drop the held view"); + assert!(after.contains("m1"), "{event} must serve the file as it is now: {after}"); + } + } + + #[test] + fn the_view_cache_holds_a_handful_of_files_and_a_bounded_amount_of_text() { + let tree = Tree::new("viewbound"); + let paths: Vec = (0..MAX_VIEWS + 2) + .map(|n| { + tree.write(&format!("f{n}.sv"), &versioned(n + 1)); + tree.path.join(format!("f{n}.sv")) + }) + .collect(); + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![tree.path.clone()]); + for path in &paths { + let _ = ws.file_view(path).expect("readable"); + } + assert_eq!(ws.views.borrow().len(), MAX_VIEWS, "the count bound holds"); + assert_eq!( + ws.views.borrow()[0].path, + paths[paths.len() - 1], + "newest first, so the oldest is what falls off" + ); + + // One file bigger than the whole byte budget: it is still cached — + // it is exactly the file this cache exists for — and it evicts + // everything else rather than being refused. + tree.write("huge.sv", &"// filler\n".repeat(MAX_VIEW_BYTES / 10 + 1)); + let huge = tree.path.join("huge.sv"); + let _ = ws.file_view(&huge).expect("readable"); + let views = ws.views.borrow(); + assert_eq!(views.len(), 1, "a file over the budget holds the cache alone"); + assert_eq!(views[0].path, huge); + } + + /// QA (2026-08-28): the bound test above only ever caches *one* oversized + /// file. The "newest is kept whatever it weighs" rule is only a bound — + /// not a leak — if a *second* oversized file replaces the first rather + /// than piling up beside it, which is the scenario the brief asks for by + /// name. + #[test] + fn a_second_oversized_file_evicts_the_first_rather_than_growing_beside_it() { + let tree = Tree::new("viewhugehuge"); + let filler = "// filler\n".repeat(MAX_VIEW_BYTES / 10 + 1); + tree.write("huge_a.sv", &filler); + tree.write("huge_b.sv", &filler); + let a = tree.path.join("huge_a.sv"); + let b = tree.path.join("huge_b.sv"); + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![tree.path.clone()]); + + let _ = ws.file_view(&a).expect("readable"); + assert_eq!(ws.views.borrow().len(), 1, "the first huge file holds the cache alone"); + let _ = ws.file_view(&b).expect("readable"); + let views = ws.views.borrow(); + assert_eq!( + views.len(), + 1, + "the second huge file replaces it rather than growing beside it" + ); + assert_eq!(views[0].path, b, "the newest is what survives"); + } + + /// QA (2026-08-28): `update_one`'s doc comment and the README both say it + /// drops *that path's* view and nothing else — the selectivity half of + /// the invalidation story, which `every_way_a_files_text_can_move_drops_ + /// its_view` never exercises because it only ever warms one file's view + /// at a time. A regression that widened `update_one` to `views.clear()` + /// would still pass every existing test in this file. + #[test] + fn updating_one_file_leaves_another_files_cached_view_alone() { + let tree = Tree::new("viewupdateoneselective"); + tree.write("a.sv", &versioned(1)); + tree.write("b.sv", &versioned(1)); + let a = tree.path.join("a.sv"); + let b = tree.path.join("b.sv"); + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![tree.path.clone()]); + + let view_a = ws.file_view(&a).expect("readable").text.clone(); + let view_b = ws.file_view(&b).expect("readable").text.clone(); + + tree.write("a.sv", &versioned(2)); + tree.write("b.sv", &versioned(2)); + assert!(ws.update_one(&a), "the index holds a.sv"); + + assert_ne!(ws.file_view(&a).expect("readable").text, view_a, "a.sv's view was dropped"); + assert_eq!( + ws.file_view(&b).expect("readable").text, + view_b, + "b.sv's view must survive a.sv's update — update_one names one path, not the cache" + ); + } + + /// QA (2026-08-28): `cached_view` moves a hit to the front so recency, + /// not merely insertion order, decides what falls off — untested until + /// now. Warm four files (the cap), touch the oldest again, then add a + /// fifth: without the recency reorder the just-touched file would be the + /// one to go (it was inserted first), and with it the file nobody has + /// asked about since is what goes instead. + #[test] + fn re_hovering_the_oldest_cached_file_saves_it_from_eviction() { + let tree = Tree::new("viewmru"); + let paths: Vec = (0..MAX_VIEWS + 1) + .map(|n| { + tree.write(&format!("f{n}.sv"), &versioned(n + 1)); + tree.path.join(format!("f{n}.sv")) + }) + .collect(); + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![tree.path.clone()]); + // Fill the cache: f0 (oldest) through f3 (newest of the first batch). + for path in &paths[..MAX_VIEWS] { + let _ = ws.file_view(path).expect("readable"); + } + // Touch the oldest again — it should now count as the most recent. + let _ = ws.file_view(&paths[0]).expect("readable"); + // One more file arrives, forcing an eviction. + let _ = ws.file_view(&paths[MAX_VIEWS]).expect("readable"); + + let paths_held: std::collections::HashSet = + ws.views.borrow().iter().map(|v| v.path.clone()).collect(); + assert!( + paths_held.contains(&paths[0]), + "the file re-hovered a moment ago must survive: {paths_held:?}" + ); + assert!( + !paths_held.contains(&paths[1]), + "the file nobody has touched since must be what falls off instead: {paths_held:?}" + ); + } + #[test] fn a_root_added_mid_session_widens_the_scan_and_a_removed_one_narrows_it() { let first = Tree::new("rootsfirst"); diff --git a/crates/lucisv_server/tests/e2e.rs b/crates/lucisv_server/tests/e2e.rs index 8eecdec..bda6e7b 100644 --- a/crates/lucisv_server/tests/e2e.rs +++ b/crates/lucisv_server/tests/e2e.rs @@ -4825,3 +4825,90 @@ fn a_keystroke_round_trip_over_the_wire() { let _ = std::fs::remove_dir_all(&dir); } } + +/// `cargo test --release -p lucisv_server --test e2e a_hover_issued -- --ignored --nocapture --test-threads=1` +#[test] +#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"] +fn a_hover_issued_during_the_initial_scan_waits_for_it() { + // Suspect 2 of the hover-latency round, measured rather than argued: + // `Server::new` runs the whole startup scan *before* `run()`'s message + // loop takes its first message, so anything a client sends the moment it + // has sent `initialized` sits in the OS pipe until that scan is done. The + // number below is what a user feels when they hover the first thing they + // see after opening a folder. + // + // A `lucisv.toml` naming a filelist is what makes the startup scan index + // the whole tree: it is the top rung of the scope ladder and the only one + // that answers before any buffer has been opened. + let dir = temp_dir("firsthover"); + let files = 200usize; + let mut list = String::new(); + for n in 0..files { + let name = format!("m{n}.sv"); + std::fs::write(dir.join(&name), generated_module(&format!("m{n}"), 1_000)).expect("write"); + list.push_str(&format!("{name}\n")); + } + std::fs::write(dir.join("files.f"), &list).expect("write"); + let top = "module top;\n m7 u (.data_in(32'h0));\nendmodule\n"; + let top_path = dir.join("top.sv"); + std::fs::write(&top_path, top).expect("write"); + std::fs::write(dir.join("lucisv.toml"), "filelist = \"files.f\"\n").expect("write"); + // `top.sv` is not in the filelist, so it is not indexed — but it is what + // the hover is *issued from*, and a buffer is indexed by being opened. + std::fs::write(dir.join("files.f"), format!("{list}top.sv\n")).expect("write"); + + let root = format!("file://{}", dir.display()); + let uri = format!("file://{}", top_path.display()); + let hover = |id: u32| { + format!( + r#"{{"jsonrpc":"2.0","id":{id},"method":"textDocument/hover","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":1,"character":3}}}}}}"# + ) + }; + + // Two whole sessions over the same storage folder: the first fills the + // persistent index cache, the second reads it. Both are measured, because + // "does the cache fix this?" is the second half of the question — it makes + // the scan cheaper, and the first hover still waits out whatever is left. + let mut took = Vec::new(); + for session in 0..2 { + let mut live = Live::start(); + live.send(&format!( + r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}},"initializationOptions":{{"storagePath":"{}"}}}}}}"#, + dir.join("storage").display() + )); + live.wait_for(|m| m["id"] == 1); + + // Everything a client sends the instant the handshake is done, in one + // go — which is exactly what VS Code does with the editor already open. + let started = std::time::Instant::now(); + live.send(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#); + live.send(&format!( + r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, + serde_json::to_string(top).expect("json") + )); + live.send(&hover(2)); + let first = live.wait_for(|m| m["id"] == 2); + let queued_behind_the_scan = started.elapsed(); + assert!( + format!("{first:#?}").contains("m7.sv"), + "the hover must really answer across files: {first:#?}" + ); + + // The same hover, with the scan long finished. + let started = std::time::Instant::now(); + live.send(&hover(3)); + live.wait_for(|m| m["id"] == 3); + let after_the_scan = started.elapsed(); + + live.finish(); + took.push((session, queued_behind_the_scan, after_the_scan)); + } + for (session, behind, after) in took { + let store = if session == 0 { "cold store" } else { "warm store" }; + eprintln!( + "hover issued the moment `initialized` was sent, over {files} files of 1k lines \ + ({store}): {behind:?}; the same hover once the scan is done: {after:?}" + ); + } + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/vlog_semantic/src/facts.rs b/crates/vlog_semantic/src/facts.rs index bb52ba3..4d0e0e6 100644 --- a/crates/vlog_semantic/src/facts.rs +++ b/crates/vlog_semantic/src/facts.rs @@ -20,13 +20,13 @@ use vlog_parser::defines::{Define, DefineKind, DefineTable}; use vlog_parser::span::TextRange; use crate::model::SymbolKind; -use crate::workspace::{Decl, DeclSite, FileFacts, ReferenceFact, SiteFact}; +use crate::workspace::{Decl, DeclLines, DeclSite, FileFacts, ReferenceFact, SiteFact}; /// The version of the encoding below. Bump it on **any** change to what a /// record holds or to how it is written: a store stamped with another number /// is discarded whole, which is the only way a reader can be sure it is not /// reading last month's field order as this month's. -pub const FACTS_FORMAT: u32 = 3; +pub const FACTS_FORMAT: u32 = 4; impl FileFacts { /// These facts as one line's worth of fields, tab-separated. @@ -197,6 +197,13 @@ impl Writer { self.num(0); } } + // The declaration's lines, on the same unconditional-pair rule: the + // name's line, then the detail span's or `0` for the `None` above. + // `FACTS_FORMAT` is bumped for these two fields, so a store written + // before them is discarded rather than read short by two + // (`docs/features/hover-line-index/README.md`). + self.num(decl.lines.name); + self.num(decl.lines.detail.unwrap_or(0)); } fn site(&mut self, site: &DeclSite) { @@ -317,7 +324,14 @@ impl<'a> Reader<'a> { let start = self.num()?; let end = self.num()?; let detail_span = (start != 0 || end != 0).then_some(TextRange::new(start, end)); - Some(Decl { name, name_span, kind, detail_span }) + // A line is 1-based, so `0` is the `None` here too — and a detail line + // is present exactly when a detail span is, which a record written by + // this format always agrees with. + let name_line = self.num()?; + let detail_line = self.num()?; + let lines = + DeclLines { name: name_line, detail: (detail_line != 0).then_some(detail_line) }; + Some(Decl { name, name_span, kind, detail_span, lines }) } fn site(&mut self) -> Option { diff --git a/crates/vlog_semantic/src/lib.rs b/crates/vlog_semantic/src/lib.rs index a9ff13b..5cc8beb 100644 --- a/crates/vlog_semantic/src/lib.rs +++ b/crates/vlog_semantic/src/lib.rs @@ -31,9 +31,9 @@ pub use model::{ SymbolId, SymbolKind, }; pub use workspace::{ - index_order, resolve_external, DeclSite, Def, Definition, DefinitionKey, ExternalResolutions, - ExternalTarget, FileFacts, FileId, IndexBuilder, IndexCounts, InheritanceEdge, - InstantiationEdge, ReferenceSite, WorkspaceIndex, WorkspaceSymbol, + index_order, resolve_external, DeclLines, DeclSite, Def, Definition, DefinitionKey, + ExternalResolutions, ExternalTarget, FileFacts, FileId, IndexBuilder, IndexCounts, + InheritanceEdge, InstantiationEdge, ReferenceSite, WorkspaceIndex, WorkspaceSymbol, }; use std::collections::HashMap; diff --git a/crates/vlog_semantic/src/workspace.rs b/crates/vlog_semantic/src/workspace.rs index 2dfb7eb..e121d2b 100644 --- a/crates/vlog_semantic/src/workspace.rs +++ b/crates/vlog_semantic/src/workspace.rs @@ -19,7 +19,7 @@ use std::path::{Path, PathBuf}; use vlog_parser::ast::SourceFile; use vlog_parser::defines::{collect_defines, Define, DefineKind, DefineTable}; use vlog_parser::span::TextRange; -use vlog_parser::{parse_source_tolerant, parse_tolerant, tokenize}; +use vlog_parser::{parse_source_tolerant, parse_tolerant, tokenize, LineIndex}; use crate::model::{ReferenceId, Resolution, Symbol, SymbolKind}; use crate::{analyze, classes, instantiations, Semantics}; @@ -41,6 +41,44 @@ pub struct Def { /// non-ANSI port's body `input wire clk;`. A cross-file hover shows these /// lines; `None` for every declaration complete where it is named. pub detail_span: Option, + /// Which lines those spans fall on, read while the file was indexed. + pub lines: DeclLines, +} + +/// Where a declaration sits in its file, counted in **lines**, computed when +/// that file is indexed. +/// +/// The index keeps no file text, so before this every `file:line` a server +/// printed for an indexed declaration cost a read of the declaring file and a +/// whole [`LineIndex`] over it — the thing a cross-file hover into a closed +/// file was mostly spending its time on. A line is four bytes per declaration, +/// a few tens of KB for a workspace of 20 000 modules, and it is the whole of +/// what a heading needs. +/// +/// **One value per declaration, so it extends by gaining a field.** Members +/// are [`Decl`]s exactly as units are, so a module's ports already carry their +/// own lines here; a column, or a rendered preview, is another field written +/// beside these two — plus the [`crate::FACTS_FORMAT`] bump any change to a +/// record owes — and not a second table to keep in step with this one. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct DeclLines { + /// 1-based line the declared name is on. + pub name: u32, + /// 1-based line the `detail_span` starts on, `None` exactly when there is + /// no detail span. + pub detail: Option, +} + +impl DeclLines { + /// The lines a declaration's spans fall on, read off its file's line + /// index. 1-based, so `name` is what `LineIndex::line_col` reports and + /// what a `file:line` prints. + fn of(lines: &LineIndex, name_span: TextRange, detail_span: Option) -> DeclLines { + DeclLines { + name: lines.line_col(name_span.start).0, + detail: detail_span.map(|span| lines.line_col(span.start).0), + } + } } /// Stable identity of one indexed declaration inside the current index. @@ -441,13 +479,15 @@ impl WorkspaceIndex { } for symbol in self.workspace_symbols("") { out.push_str(&format!( - "sym {} in {:?} {:?} {}:{}..{}\n", + "sym {} in {:?} {:?} {}:{}..{} line={} detail={:?}\n", symbol.name, symbol.container, symbol.def.kind, symbol.def.file.0, symbol.def.name_span.start, - symbol.def.name_span.end + symbol.def.name_span.end, + symbol.def.lines.name, + symbol.def.lines.detail )); } for (definition, sites) in &self.reference_sites { @@ -661,20 +701,28 @@ pub(crate) struct Decl { pub(crate) name_span: TextRange, pub(crate) kind: SymbolKind, pub(crate) detail_span: Option, + pub(crate) lines: DeclLines, } impl Decl { - fn of(symbol: &Symbol) -> Decl { + fn of(symbol: &Symbol, lines: &LineIndex) -> Decl { Decl { name: symbol.name.clone(), name_span: symbol.name_span, kind: symbol.kind, detail_span: symbol.detail_span, + lines: DeclLines::of(lines, symbol.name_span, symbol.detail_span), } } fn def(&self, file: FileId) -> Def { - Def { file, name_span: self.name_span, kind: self.kind, detail_span: self.detail_span } + Def { + file, + name_span: self.name_span, + kind: self.kind, + detail_span: self.detail_span, + lines: self.lines, + } } } @@ -757,15 +805,21 @@ impl FileFacts { /// server holding an open buffer's finished analysis) gets the record the /// parse would have produced without paying for the parse a second time. /// The two paths are the same code and cannot drift; what the caller - /// promises is only that `tree`, `defines` and `sem` are the analysis of + /// promises is only that `tree`, `defines`, `sem` and `lines` all describe /// the text `path` currently holds. + /// + /// `lines` is asked for rather than built here because a caller with a + /// finished analysis in hand — a server holding an open buffer — already + /// has one, and because a record now carries each declaration's line + /// ([`DeclLines`]). pub fn from_analysis( path: PathBuf, tree: &SourceFile, defines: &DefineTable, sem: &Semantics, + lines: &LineIndex, ) -> FileFacts { - facts_from_analysis(path, tree, defines.clone(), sem) + facts_from_analysis(path, tree, defines.clone(), sem, lines) } /// The file these facts were read from. @@ -778,7 +832,11 @@ impl FileFacts { fn facts_of(path: PathBuf, src: &str) -> FileFacts { let (tree, defines) = parse_and_collect(src); let sem = analyze(&tree, src); - facts_from_analysis(path, &tree, defines, &sem) + // One pass over the source's newlines, so every declaration below can be + // given its line without anyone reading the file again later. It is a + // percent of the parse it sits beside (`docs/perf/README.md`). + let lines = LineIndex::new(src); + facts_from_analysis(path, &tree, defines, &sem, &lines) } /// Read off what one file contributes, from its finished analysis. @@ -787,6 +845,7 @@ fn facts_from_analysis( tree: &SourceFile, defines: DefineTable, sem: &Semantics, + lines: &LineIndex, ) -> FileFacts { let mut facts = FileFacts { path, @@ -807,8 +866,8 @@ fn facts_from_analysis( if !is_unit(unit.kind) || unit.name_span.is_empty() { continue; } - facts.units.push(Decl::of(unit)); - collect_members(sem, unit, &mut facts.members); + facts.units.push(Decl::of(unit, lines)); + collect_members(sem, unit, lines, &mut facts.members); } let exported: HashSet<(u32, u32)> = facts .units @@ -889,7 +948,12 @@ fn inheritance_of(tree: &SourceFile) -> Vec<(String, DeclSite)> { } /// Read off the names another file may reach *into* this unit for. -fn collect_members(sem: &Semantics, unit: &Symbol, out: &mut Vec<(String, Decl)>) { +fn collect_members( + sem: &Semantics, + unit: &Symbol, + lines: &LineIndex, + out: &mut Vec<(String, Decl)>, +) { let Some(scope) = unit.child_scope.and_then(|c| sem.scope(c)) else { return; }; @@ -900,13 +964,13 @@ fn collect_members(sem: &Semantics, unit: &Symbol, out: &mut Vec<(String, Decl)> if !is_exported(unit.kind, member.kind) || member.name_span.is_empty() { continue; } - out.push((unit.name.clone(), Decl::of(member))); + out.push((unit.name.clone(), Decl::of(member, lines))); // A class nested in a package (the dominant UVM shape) is not a unit, // but an external `cls::x` candidate looks its members up under the // *class's* name — register them there too. The scope tree is acyclic, // so this recursion terminates. if member.kind == SymbolKind::Class { - collect_members(sem, member, out); + collect_members(sem, member, lines, out); } } } diff --git a/crates/vlog_semantic/tests/workspace.rs b/crates/vlog_semantic/tests/workspace.rs index a704057..ae9b6ef 100644 --- a/crates/vlog_semantic/tests/workspace.rs +++ b/crates/vlog_semantic/tests/workspace.rs @@ -1554,6 +1554,149 @@ fn a_records_every_field_survives_the_round_trip() { assert_eq!(back.encode(), Some(line), "and re-encodes byte for byte"); } +/// Every indexed declaration carries the line it is written on, so a caller +/// printing `file:line` never has to read the file +/// (`docs/features/hover-line-index/README.md`). The awkward offsets are the +/// point: line 1 has no newline before it, the last line has none after it, +/// and both are where an off-by-one lives. +#[test] +fn every_declared_names_line_is_recorded_when_the_file_is_indexed() { + // No trailing newline, so `last_t` really is on the file's last line. + let src = "module first;\nendmodule\n\n// a comment\npackage p;\n localparam W = 8;\n\ + endpackage\ntypedef int last_t;"; + let index = index(&[("/w/m.sv", src)]); + let line_of = |name: &str| index.units(name).first().expect(name).lines.name; + assert_eq!(line_of("first"), 1, "a declaration on line 1"); + assert_eq!(line_of("p"), 5); + assert_eq!(line_of("last_t"), 8, "the last line, with no newline after it"); + assert_eq!(index.member("p", "W").first().expect("W").lines.name, 6, "members too"); + + // The line really is the line the text says it is: every recorded line's + // range, sliced out of the source, contains the name it was recorded for. + for (name, line) in [("first", 1), ("p", 5), ("last_t", 8)] { + let text = src.lines().nth(line as usize - 1).expect("that many lines"); + assert!(text.contains(name), "line {line} is {text:?}, which does not declare {name}"); + } +} + +/// A `\r\n` file and multi-byte text before a declaration do not shift its +/// line: lines are counted in newlines, not in bytes or in characters. +#[test] +fn crlf_and_multibyte_text_do_not_shift_a_declarations_line() { + let crlf = "// one\r\n// two\r\nmodule m;\r\nendmodule\r\n"; + assert_eq!(index(&[("/w/c.sv", crlf)]).units("m").first().expect("m").lines.name, 3); + + // Three-byte characters and a four-byte emoji ahead of the declaration: + // the byte offset of `m` is far past 3, its line is not. + let wide = "// héllo ✓ 🎉\n// ünïcödé\nmodule m;\nendmodule\n"; + assert!(wide.find("module m").expect("a module") > 20, "premise: the bytes are wide"); + assert_eq!(index(&[("/w/w.sv", wide)]).units("m").first().expect("m").lines.name, 3); +} + +/// A non-ANSI port is named in the header and finished in the body, and the +/// carrier holds a line for each — the extension the shape was chosen for: +/// richer per-declaration position data is another field on `DeclLines`, not +/// another table. +#[test] +fn a_split_ports_two_lines_ride_the_same_carrier() { + let src = "module m (\n clk\n);\n input wire clk;\nendmodule\n"; + let split = index(&[("/w/s.sv", src)]); + let def = split.member("m", "clk").first().expect("the port"); + assert!(def.detail_span.is_some(), "premise: this port is split"); + assert_eq!(def.lines.name, 2, "the header names it on line 2"); + assert_eq!(def.lines.detail, Some(4), "and the body finishes it on line 4"); + + // An ANSI port is complete where it is named, and says so in both fields. + let ansi = index(&[("/w/a.sv", "module m (\n input wire clk\n);\nendmodule\n")]); + let def = ansi.member("m", "clk").first().expect("the port"); + assert_eq!(def.detail_span, None); + assert_eq!((def.lines.name, def.lines.detail), (2, None)); +} + +/// The lines survive the record format, which is what makes them free on a +/// cached scan rather than only on a parsed one. +#[test] +fn a_declarations_lines_survive_the_record_round_trip() { + let src = "module m (\n clk\n);\n input wire clk;\nendmodule\n"; + let facts = FileFacts::of(PathBuf::from("/w/s.sv"), src); + let line = facts.encode().expect("encodes"); + let back = FileFacts::decode(&line).expect("decodes"); + assert_eq!(back, facts, "every field, lines included"); + + let mut builder = vlog_semantic::IndexBuilder::new(); + builder.add_facts(back); + let restored = builder.finish(); + let def = restored.member("m", "clk").first().expect("the port"); + assert_eq!((def.lines.name, def.lines.detail), (2, Some(4))); +} + +/// QA (2026-08-28): the single-decl fixture `index_cache`'s own format-bump +/// test strips is not the only shape a genuine format-3 record could take — +/// a file declaring *two* units is the shape where a field-shift attack would +/// actually have somewhere plausible to land: if stripping the first decl's +/// two line fields shifted every read two fields early, the fields it would +/// then misread as `(name_line, detail_line)` are the *second* decl's own +/// `name` and `kind` strings. Both are always non-numeric — a Verilog +/// identifier cannot start with a digit and `kind_name` writes only letters — +/// so `Reader::num` fails on them and `decode` returns `None` rather than +/// quietly building a `Decl` out of someone else's fields. Proved directly +/// here, generalizing `index_cache`'s stripper to more than one declaration, +/// rather than only argued. +#[test] +fn a_format_3_record_with_two_declarations_is_rejected_not_misread() { + let src = "module a; endmodule\nmodule b; endmodule\n"; + let facts = FileFacts::of(PathBuf::from("/w/two.sv"), src); + let encoded = facts.encode().expect("encodes"); + let format_3 = strip_every_decls_line_fields(&encoded, 2, 0); + assert_ne!(format_3, encoded, "premise: fields were actually removed"); + assert!( + FileFacts::decode(&format_3).is_none(), + "a two-unit format-3 record decoded as a format-4 one: {format_3}" + ); + + // The mixed case: one unit with a member that has a real detail span (a + // split port), so the decls being stripped are not even the same width + // of *content* — only of field count, which is what the format promises. + let split = "module m (\n clk\n);\n input wire clk;\nendmodule\n\ + module other; endmodule\n"; + let facts = FileFacts::of(PathBuf::from("/w/mixed.sv"), split); + let encoded = facts.encode().expect("encodes"); + let format_3 = strip_every_decls_line_fields(&encoded, 2, 1); + assert_ne!(format_3, encoded, "premise: fields were actually removed"); + assert!( + FileFacts::decode(&format_3).is_none(), + "a mixed unit+member format-3 record decoded as a format-4 one: {format_3}" + ); +} + +/// The generalization of `index_cache`'s `strip_the_line_fields`: remove the +/// two trailing (`name_line`, `detail_line`) fields from every one of +/// `units` unit-decls and `members` member-decls in an encoded record — +/// i.e. what `FACTS_FORMAT` 3 wrote for the same file. Assumes `D0` (no +/// `` `define``s), which every fixture here satisfies, so the `U` tag's +/// field index is fixed and decl positions can be computed directly rather +/// than parsed. +fn strip_every_decls_line_fields(encoded: &str, units: usize, members: usize) -> String { + let mut fields: Vec<&str> = encoded.split('\t').collect(); + let units_at = fields.iter().position(|f| *f == "U").expect("a U tag"); + assert_eq!(fields[units_at + 1], units.to_string(), "premise: unit count"); + // decl = name, kind, name_span×2, detail_span×2, line×2 — 8 fields. + let unit_decls_end = units_at + 2 + units * 8; + let members_at = unit_decls_end; + assert_eq!(fields[members_at], "M", "premise: members tag follows the units"); + assert_eq!(fields[members_at + 1], members.to_string(), "premise: member count"); + // A member entry is the owning unit's name (one text field) plus a decl. + let member_decl_starts: Vec = (0..members).map(|m| members_at + 2 + m * 9 + 1).collect(); + let unit_decl_starts: Vec = (0..units).map(|u| units_at + 2 + u * 8).collect(); + // Highest index first, so removing one strip does not move the others. + let mut starts: Vec = unit_decl_starts.into_iter().chain(member_decl_starts).collect(); + starts.sort_unstable_by(|a, b| b.cmp(a)); + for start in starts { + fields.drain(start + 6..start + 8); + } + fields.join("\t") +} + #[test] fn an_index_built_from_records_is_the_index_the_parse_would_have_given() { // The claim the cache rests on: facts through the record format and back @@ -1668,7 +1811,9 @@ fn a_degenerate_file_still_makes_a_record() { /// `lucisv_server::state::Document::new` builds it — one lex, the tree from a /// clone of that token stream, the define table off the same tokens, and the /// same all-or-nothing lex-failure branch. -fn as_a_server_analyzes(src: &str) -> (vlog_parser::ast::SourceFile, DefineTable, Semantics) { +fn as_a_server_analyzes( + src: &str, +) -> (vlog_parser::ast::SourceFile, DefineTable, Semantics, vlog_parser::LineIndex) { let (tokens, tree) = match tokenize(src) { Ok(tokens) => { let (tree, _) = parse_tolerant(tokens.clone(), src); @@ -1678,7 +1823,7 @@ fn as_a_server_analyzes(src: &str) -> (vlog_parser::ast::SourceFile, DefineTable }; let defines = collect_defines(&tokens); let sem = analyze(&tree, src); - (tree, defines, sem) + (tree, defines, sem, vlog_parser::LineIndex::new(src)) } /// `FileFacts::from_analysis` and `FileFacts::of` are one record, not two. @@ -1720,9 +1865,9 @@ fn facts_from_a_finished_analysis_are_byte_identical_to_facts_from_the_text() { ]; for src in crafted { let path = PathBuf::from("/w/x.sv"); - let (tree, defines, sem) = as_a_server_analyzes(src); + let (tree, defines, sem, lines) = as_a_server_analyzes(src); let from_text = FileFacts::of(path.clone(), src); - let from_analysis = FileFacts::from_analysis(path, &tree, &defines, &sem); + let from_analysis = FileFacts::from_analysis(path, &tree, &defines, &sem, &lines); assert_eq!(from_analysis, from_text, "the records differ for {src:?}"); assert_eq!( from_analysis.encode(), @@ -1750,9 +1895,9 @@ fn the_two_ways_to_read_a_files_facts_agree_over_the_whole_corpus() { let Ok(src) = std::fs::read_to_string(path) else { continue; }; - let (tree, defines, sem) = as_a_server_analyzes(&src); + let (tree, defines, sem, lines) = as_a_server_analyzes(&src); let from_text = FileFacts::of(path.clone(), &src); - let from_analysis = FileFacts::from_analysis(path.clone(), &tree, &defines, &sem); + let from_analysis = FileFacts::from_analysis(path.clone(), &tree, &defines, &sem, &lines); assert_eq!( from_analysis.encode(), from_text.encode(), @@ -1799,8 +1944,14 @@ fn an_index_built_from_finished_analyses_fingerprints_the_same_as_one_built_from let mut builder = vlog_semantic::IndexBuilder::new(); // Deliberately not path order: the reuse must not smuggle an ordering in. for (path, src) in files.iter().rev() { - let (tree, defines, sem) = as_a_server_analyzes(src); - builder.add_facts(FileFacts::from_analysis(PathBuf::from(*path), &tree, &defines, &sem)); + let (tree, defines, sem, lines) = as_a_server_analyzes(src); + builder.add_facts(FileFacts::from_analysis( + PathBuf::from(*path), + &tree, + &defines, + &sem, + &lines, + )); } let from_analyses = builder.finish(); assert_eq!(from_analyses.fingerprint(), from_text.fingerprint()); @@ -1809,12 +1960,13 @@ fn an_index_built_from_finished_analyses_fingerprints_the_same_as_one_built_from // index `update_file` would have left. let mut updated = from_text.clone(); let changed = "package p;\n localparam W = 16;\n class c; int y; endclass\nendpackage\n"; - let (tree, defines, sem) = as_a_server_analyzes(changed); + let (tree, defines, sem, lines) = as_a_server_analyzes(changed); updated.update_facts(FileFacts::from_analysis( PathBuf::from("/w/pkg.sv"), &tree, &defines, &sem, + &lines, )); let mut parsed = from_text.clone(); parsed.update_file(PathBuf::from("/w/pkg.sv"), changed); diff --git a/docs/features/hover-declarations/README.md b/docs/features/hover-declarations/README.md index c8b57c1..c397da5 100644 --- a/docs/features/hover-declarations/README.md +++ b/docs/features/hover-declarations/README.md @@ -64,6 +64,10 @@ entirely whenever it could be the wrong line. bumps `FACTS_FORMAT` 2 → 3, so a store written before *that* round is discarded. This round's own promise held while it was this round's to make; the index is text-free either way (a span is not text). + **Superseded again 2026-08-28 by `docs/features/hover-line-index/README.md`**, + which adds `Def::lines` (each declaration's line number) and bumps + `FACTS_FORMAT` 3 → 4. Same reading: a line number is not text either, and + it is what makes this feature's heading free. - The heading line `**label** — declared in `file:line`` is unchanged, so a client (or a test) reading only that half sees exactly what it saw before. @@ -131,6 +135,10 @@ The character cap counts `char`s and cuts on a boundary. tie-break pinned by test. - [x] **2026-08-28**: a CRLF file's snippet no longer carries an interior `\r` into the fence; QA finding 2 closed. +- [x] **2026-08-28** (`docs/features/hover-line-index/README.md`): the disk + path's heading costs no read at all (`Def::lines`) and its snippet's + read is shared across hovers, so the second hover into a closed file is + free. `disk_view` is gone, subsumed by `Workspace::file_view`. ## Work log @@ -230,6 +238,32 @@ with less work. Numbers in `docs/perf/README.md`. - Cost: four bytes per symbol. Measured saving on the lookup alone: 8.41 µs → 133 ns over a 5 001-symbol file (`docs/perf/README.md`). +### 2026-08-28 — dev (the heading stops reading the file at all) + +Round `hover-line-index` — full argument, measurements and tests in +`docs/features/hover-line-index/README.md`. What changed *here*: + +- **The `External` arm's disk branch no longer reads anything for the + heading.** `Def` now carries `lines: DeclLines`, recorded when the file was + indexed, so `**port** — declared in `sub.sv:2`` is a field lookup. The live + branch is untouched and still asks the open buffer's own line index, because + that buffer may hold unsaved edits the index has not seen — the same reason + `declaration_snippet` matches a `Def` to a live symbol logically. +- **`disk_view` was deleted.** Its job — one read per file per hover — is now + `Workspace::file_view`'s, which does it once per file per *generation of that + file*, so the next hover into the same file reads nothing. The four points + that drop a held view are listed in that round's Handshakes. +- **`spells_exactly` and both caps are untouched**, and a stale held view can + only ever make a snippet vanish. Every existing test in this file passed + unmodified. +- **One corner moved deliberately**: a closed file that cannot be *read* now + still gets its line in the heading (`sub.sv:2` rather than a bare `sub.sv`), + because the line no longer depends on the read. Pinned by + `a_closed_files_heading_line_comes_from_the_index_and_not_from_a_read`. +- Measured: a hover into a 12 MB closed file, 6.2 ms → **0.95 µs** on the + second hover; the 31.7 MB probe above, 17.0 ms → **4.4 µs** on the second. + The first touch is unchanged, because the snippet genuinely wants the text. + ### 2026-08-28 — dev (CRLF, closing QA finding 2) - Finding 2 below — a CRLF file's multi-line snippet keeping an interior diff --git a/docs/features/hover-line-index/README.md b/docs/features/hover-line-index/README.md new file mode 100644 index 0000000..42d68e6 --- /dev/null +++ b/docs/features/hover-line-index/README.md @@ -0,0 +1,531 @@ +# hover-line-index + +## Goal + +The owner's report (2026-08-28): hovering a module instantiation is slow, and +hovering one of its ports — to see the port's own declaration — is slow on the +**first** try. Both land on the same code: a hover whose target is declared in +a *closed* file read that whole file and built a whole `LineIndex` over it, for +two things at once — the heading's `file:line`, and the fenced snippet of the +declaration. On a netlist-adjacent file that read is milliseconds, and nothing +was kept, so the *next* hover into the same file paid it again. The owner's +design, which this round implements: put each declared name's **line number** +into the index itself, where it costs a `u32` per declaration and is computed +once when the file is scanned. The heading then costs no file access at all, +and only the snippet still wants text — served from a small bounded cache of +closed files' text in `Workspace`, so the first touch pays one read and no +touch after it pays anything. + +The shape of what that buys, measured below: a hover into a 12 MB closed file +goes **6.2 ms → 0.9 µs on the second hover** and stays 6.2 ms on the first; +the steady-state cross-file hover on a 10 000-line file goes **157 µs → +13 µs**. The round also *measured the other suspect* and did not fix it — see +Handshakes. + +## Assumptions + +- **A line is a fact about the same snapshot the span is.** `Def::name_span` + and `Def::lines.name` are read off one text in one pass, so a heading and a + snippet can never name different generations of a file. Where the file has + changed on disk with nothing telling the server, both are stale together, + which is strictly better than the previous shape — a stale *offset* looked + up in *fresh* text, whose line was arbitrary. +- **Lines are 1-based, and are exactly what `LineIndex::line_col` reports.** + That is what `locate::line_number` returned before, so the same headings come + out. +- **`FileFacts::from_analysis`'s caller has a line index already.** It is a + server holding an open buffer's finished `Document`, which carries one. So + the extra parameter costs the caller nothing, and `FileFacts::of` builds its + own — one pass over the source's newlines, about 1 % of the parse it sits + beside (`docs/perf/README.md`: `LineIndex::new` 115 µs against + `parse_tolerant` 14.3 ms at 10 000 lines). +- **The view cache is a cache and never a correctness input.** Every entry can + be dropped at any moment with no change to any answer; a *stale* entry can + only ever make a snippet disappear, never make it wrong, because + `hover::spells_exactly` still checks the text at the span against the hovered + name before anything is shown. That guard is unchanged and is still the last + line of defence. +- **Only closed files are cached.** `Workspace::file_view` returns `None` for a + path an open buffer speaks for: that buffer's `Document` already holds its + text and line index, and a second copy here would be a second opinion. +- **The index is still text-free.** A line number is not text, exactly as a + span is not text (`docs/features/workspace-index/README.md`'s promise, and + the same reading `port-detail-spans` took for `detail_span`). + +## Handshakes + +### `vlog_semantic` — `DeclLines`, and the carrier's extension story + +```rust +/// Where a declaration sits in its file, counted in lines. +pub struct DeclLines { + pub name: u32, // 1-based line of the declared name + pub detail: Option, // 1-based line the detail span starts on +} + +pub struct Def { + pub file: FileId, + pub name_span: TextRange, + pub kind: SymbolKind, + pub detail_span: Option, + pub lines: DeclLines, // new +} + +// One added parameter, because a record now carries lines: +impl FileFacts { + pub fn from_analysis(path, tree, defines, sem, lines: &LineIndex) -> FileFacts; +} +pub const FACTS_FORMAT: u32 = 4; // was 3 +``` + +**The carrier is one value per declaration, and it extends by gaining a +field.** That is the owner's explicit ask ("keep the implementation flexible so +we might even cache the port location") answered structurally rather than +promised: + +- **Ports already ride it.** A module's ports and parameters are indexed as + *members*, and a member is a `Decl` exactly as a unit is — so + `index.member("sub", "addr").lines.name` is that port's line, recorded in the + same pass, with no extra table, no extra pass and no extra decision about + "small projects". The owner's optional second step was already paid for by + the first. +- **A split port's two lines ride it too.** A non-ANSI port is named in the + header and finished in the body (`detail_span`, + `docs/features/port-detail-spans/README.md`), and `DeclLines::detail` is that + body's line — the second position datum, already present, in the same value. +- **A third one is a field.** A column, a rendered preview, an end line: add it + to `DeclLines`, write it in `Writer::decl`, read it in `Reader::decl`, bump + `FACTS_FORMAT`. Nothing else moves, because nothing else knows how many + fields a `DeclLines` has. A *parallel table* keyed by declaration was the + alternative and was rejected: it would have to be kept in step with `Decl` + through every merge, every incremental update and every record round-trip, + and there is no second consumer to justify the indirection + (`CLAUDE.md`, "Simplicity first"). + +### `vlog_semantic` — `FACTS_FORMAT` 3 → 4, justified + +A record's per-declaration group grew two fields. The rule written at the +constant is that **any** change to what a record holds bumps the format, and +the reason it is a whole-store discard rather than a migration is +`docs/features/index-persistence/README.md`'s: a reader that guessed at an +older layout would read last month's field order as this month's. Concretely, +a format-3 record read as a format-4 one would shift every field after the +first declaration by two — which is why the format field in the store's header +catches it first, and why `decode` rejects it even if something served it past +the header (both pinned, see Tests). The cost is one re-parse of the workspace +on the first scan after upgrading; the corpus measurement below says that is +about 175 ms. + +### `vlog_semantic` — fingerprint + +`WorkspaceIndex::fingerprint`'s `sym` line now carries `line=` and `detail=`. +That is what makes the house witness — incremental index == fresh build — +cover the new field rather than ignore it; every existing equivalence test +(`update_file`, `update_facts`, `add_facts` from records, the corpus sweep) +now compares lines as well as spans, and all of them stayed green unmodified. + +### `lucisv_server::state` — the closed-file view cache + +```rust +pub struct FileView { pub path: PathBuf, pub text: String, pub lines: LineIndex } +impl Workspace { + pub fn file_view(&self, path: &Path) -> Option>; +} +``` + +Bounded by **four entries** and **8 MiB of text**, newest first, oldest +evicted. Two bounds because they answer two questions: how many files one +answer can name (a card names one or two; a references list walks a handful +before moving on), and how much memory a netlist-shaped file may cost. The +newest entry is kept whatever it weighs — one file can exceed the whole byte +budget on its own, and a cache that refused to hold it would be useless for +exactly the file it exists for — so a huge file simply evicts everything else. + +**Every invalidation point, in full.** A view is dropped when: + +| event | what is dropped | why | +|---|---|---| +| `set_document(uri, text)` — `didOpen`, `didChange`, a text-carrying `didSave` | that path's view | the buffer becomes the authority, and the held disk copy may predate the edits it carries | +| `close_document(uri)` | that path's view | disk is the authority again, and the view predates every save that buffer made | +| `update_one(path)` | that path's view | re-indexing one file *is* the claim its bytes moved | +| `rebuild_index_with(..)` | **all** views | a rescan says nothing about which file moved | + +Those four are every path in the server that can change what a file holds: +`server.rs` reaches the first two directly from the sync notifications, and the +last two through `reindex_one` / `reindex`, which is where a save, a watched +file change, a client file operation and a settings change all land. + +What survives all four is a file changed on disk with nothing telling this +server — and there the *index* is stale by the same event, which is precisely +what `spells_exactly` exists for. + +### `lucisv_server::locate` — the sweep + +`locate::line_number` and `locate::location` were the only two functions that +read a whole file to answer a position question, and `line_number`'s only +callers were `hover.rs`'s two. Both now take an open buffer's own line index +when there is one and the shared view otherwise; neither reads a file directly +any more. `location`'s open-buffer arm also stops cloning the whole buffer text +(`text_of` returns a `String`) on the way to a range. Mechanical, no behaviour +change: `location` is what `textDocument/definition`, references, the lens and +the hierarchies build their `Location`s from, and a references list over one +file now reads that file once instead of once per site. + +An indexed declaration's line no longer goes through `line_number` at all — +`Def::lines` is the answer. What is left for it is the spans the index records +no line for, which today is a `` `define``'s (the macro hover card's +`defined in file:line`). Those ride the shared view, so a second macro hover +into one file is free; giving `Define` its own line would mean a field in +`vlog_parser`'s `Define` and is filed rather than done — it buys the first +touch of one card and costs a second crate a field. + +### Suspect 2 — **reported, not fixed**, filed here as a handshake request + +The brief named a second suspect and asked for it to be measured and filed +rather than redesigned. It is real, and on the owner's own complaint it is by +far the larger of the two: + +`Server::new` runs the whole startup scan **before** `run()`'s message loop +takes its first message. `main.rs` answers `initialize` (through +`initialize_finish`, which also consumes `initialized`) and only then builds +the `Server` — so everything a client sends the instant the handshake is done +sits in the OS pipe until the scan is over. Measured over a 200-file, 1 000- +line-each workspace with a filelist (so the startup scan really indexes it): + +| the first hover of a session | cold store | warm store | +|---|---:|---:| +| issued the moment `initialized` was sent | **780 ms** | **287 ms** | +| the same hover once the scan is done | 64 µs | 61 µs | + +Four orders of magnitude, and this round does not touch it: fixing it means +answering requests during the scan (or scanning on another thread), which is a +change to request scheduling and to what an answer *means* while the index is +half-built. `docs/features/index-persistence`'s store already takes it from +780 ms to 287 ms; the rest is the read, the completion word table's lex and +the include scan, which that feature's README already names as uncached. +**Request to whoever owns the message loop next:** this is where "the first +hover is really slow" mostly lives, and the probe that measures it is +`e2e::a_hover_issued_during_the_initial_scan_waits_for_it`. + +## Measured + +Machine and method are `docs/perf/README.md`'s: Apple M1 Max, macOS 27.0, +`--release`, `#[ignore]`d probes, `--test-threads=1`, means where the numbers +are small enough to need one. Every figure below was taken on 2026-08-28, +before and after, in the same session. + +### Suspect 1 — the per-hover read + +| what | before | after | +|---|---:|---:| +| hover on an **instantiation** into a 12 MB closed file, first touch | 6.47 ms | 6.23 ms | +| — the same hover again | 5.75 ms | **0.95 µs** | +| hover on a **port** into the same file, first touch | 5.85 ms | 5.92 ms | +| — the same hover again | 5.71 ms | **0.99 µs** | +| hover into a 31.7 MB closed file, first touch (QA's own probe) | 17.0 ms | 16.8 ms | +| — the same hover again | 17.0 ms | **4.4 µs** | +| cross-file hover, 1 000-line target, mean of 20 | 39.8 µs | **4.7 µs** | +| cross-file hover, 10 000-line target, mean of 20 | 157 µs | **12.9 µs** | +| — one read + `LineIndex` of that file, for comparison | 149 µs | 158 µs | + +Read the table as two claims. **The first touch is unchanged**, and it should +be: the snippet genuinely wants that file's text, and reading it is what the +6.2 ms is. **Every touch after it is free**, which is the shape the owner's +"slow on the FIRST try" report describes — and the heading half is free even +on the first touch, which is why a card with no snippet (an unreadable file, a +guard miss) now costs nothing at all. + +### The price paid for it + +| | before | after | +|---|---:|---:| +| whole 860-file corpus scan, no cache | 338 ms | 343 ms | +| — cold, filling the store | 372 ms | 374 ms | +| — warm, every file from the store | 197 ms | 200 ms | +| the store, 860 files | 2 312 802 B | 2 380 790 B | + +The scan times are inside their own run-to-run noise: the added work is one +`LineIndex::new` per parsed file, which the flush breakdown puts at under 1 % +of that file's parse. The store grows **68 KB over 860 files — 2.9 %**, which +is the two decimal numbers per declaration over roughly 13 000 declarations, +and is the owner's "a few KB for 20 000 modules" measured on real source. + +## Status / TODO + +- [x] Measure both suspects before touching anything; both recorded above. +- [x] `DeclLines` on `Decl` and on `Def`, computed in `facts_from_analysis` + from the file's own `LineIndex`. +- [x] `FileFacts::from_analysis` takes the line index; `FileFacts::of` builds + one. +- [x] Record codec: two fields per declaration, `FACTS_FORMAT` 3 → 4, with the + justification above. +- [x] `WorkspaceIndex::fingerprint` carries the lines, so incremental == fresh + covers them. +- [x] `Workspace::file_view` — bounded, LRU, four named invalidation points. +- [x] `hover.rs`: heading from `Def::lines`, snippet from the shared view; the + per-request `disk_view` memo is gone, subsumed. +- [x] `locate.rs` swept onto the buffer's index / the shared view. +- [x] Tests (11 new, listed in the work log) and two new `#[ignore]`d probes. +- [x] `cargo fmt` / `cargo clippy --all-targets` / `cargo test --workspace`. +- [ ] **Not done, deliberately: `` `define``s get no indexed line.** A + `Define` is `vlog_parser`'s, and giving it a line means a field in + another crate's public type plus its own record fields, to save the + *first* macro hover into one file and nothing after it. The shared view + already covers the repeat. +- [ ] **Not done, deliberately: the other `text_of` callers are untouched.** + `rename`, `ports`, `hierarchy`, `type_hierarchy`, `completion`, + `signature`, `inlay` and `nav` read whole files because they want whole + files, not a line — the sweep was for the position-only readers. Routing + them through the view cache would mean `text_of` handing out an `Rc` + instead of a `String`, which is a different change with a different + argument. +- [ ] **Reported, not fixed: the first request of a session waits out the + startup scan.** Numbers and the filed request are in Handshakes. + +## Work log + +### 2026-08-28 — dev + +**Measured first, both suspects, before a line of the fix was written.** Two +new probes were needed and are part of the round: +`perf::hovering_into_a_big_closed_file_first_touch_and_repeat` (an +instantiation and a port, into a 12 MB file, first touch and repeat separately +— the existing probes all reported means, which hide exactly the first/repeat +split the owner's report is about) and +`e2e::a_hover_issued_during_the_initial_scan_waits_for_it` (over the wire, +against the real binary, two whole sessions so the persistent store is cold in +one and warm in the other). The second answered the brief's question about +suspect 2 with a number four orders of magnitude larger than suspect 1's, which +is worth saying plainly even though this round could not act on it. + +**The carrier: a struct, not a bare `u32`.** `DeclLines { name, detail }` +rather than `line: u32` on `Decl`, because the *second* datum already exists — +a split port's body line — and because the owner asked for room for more. The +alternative shapes were both worse: a bare `u32` would have needed a second +field the day `detail` was wanted (and `detail` was wanted on day one), and a +parallel table keyed by declaration would have to be kept in step with `Decl` +through the merge, the incremental update and the record round-trip, for no +consumer that exists. `Option` for `detail` rather than a `0` sentinel in +the *type*, even though the *record* writes `0` for `None`: the record's +sentinel is a framing decision (the stream stays flat, exactly as +`detail_span`'s `0 0` already does) and the type's is an API decision, and +those two should not be forced to be the same thing. + +**`from_analysis` grew a parameter rather than growing a `&str`.** It could +have taken `src: &str` and built its own index, but its one real caller — +`Document::facts` — already holds a `LineIndex` over exactly that text, and +handing it over is both cheaper and more honest about what the function needs. +The test helper `as_a_server_analyzes` grew a fourth return value for the same +reason. + +**`FACTS_FORMAT` 3 → 4, not 2 → 3 as the brief said.** The brief was written +against a tree where `port-detail-spans` had not yet been counted; the constant +was already at 3 when this round started. Same rule, next number. + +**The heading now comes from the index on the disk path, and that is a small +behaviour change in one corner.** Before, a closed file that could not be read +produced a bare `` `sub.sv` `` heading with no line; now it produces +`` `sub.sv:2` ``, because the line no longer depends on the file being +readable. That is more information and not less, it is the line the index +recorded from the text it indexed, and it is pinned by +`a_closed_files_heading_line_comes_from_the_index_and_not_from_a_read` — which +deletes the file and requires the heading to survive. Every other card is +byte-identical: the full suite passed unmodified before a single new test was +added, including the stale-span, guard, CRLF, cap and ambiguity tests. + +**The live path was deliberately left alone.** An open buffer's heading still +comes from that buffer's own line index and *not* from `Def::lines`, because +the buffer may hold unsaved edits the index has not seen — the same reason +`declaration_snippet` matches a `Def` to a live symbol logically instead of +reading at the indexed span (`docs/features/hover-declarations/README.md`). +Zero I/O either way, so there is nothing to win by unifying them and a +correctness property to lose. + +**`disk_view` is gone, subsumed.** Its whole job — one read per file per hover +— is now the view cache's, which does the same thing per *session* instead of +per request. The per-request memo would have been a second cache in front of +the first. + +**Files touched.** `crates/vlog_semantic/src/{workspace.rs,facts.rs,lib.rs}`, +`crates/vlog_semantic/tests/workspace.rs`, +`crates/lucisv_server/src/{state.rs,locate.rs,hover.rs,index_cache.rs,perf.rs}`, +`crates/lucisv_server/tests/e2e.rs`, this README, +`docs/features/{hover-declarations,workspace-index,index-persistence}/README.md`, +`docs/perf/README.md`, `TODO.md`. No new dependency, no `unsafe`, no +`#[allow]`, no version bump, no commits. + +**Tests added.** + +| test | where | pins | +|---|---|---| +| `every_declared_names_line_is_recorded_when_the_file_is_indexed` | `vlog_semantic/tests/workspace.rs` | line 1, a middle line, the last line with no trailing newline, and a member's line — each checked against the source line's own text | +| `crlf_and_multibyte_text_do_not_shift_a_declarations_line` | same | `\r\n` line endings, and three- and four-byte characters ahead of the declaration | +| `a_split_ports_two_lines_ride_the_same_carrier` | same | the extension story: a non-ANSI port's header line *and* body line, and an ANSI port's `None` | +| `a_declarations_lines_survive_the_record_round_trip` | same | encode → decode → equal, and through `IndexBuilder` to a `Def` | +| `a_store_from_any_previous_facts_format_is_dropped_not_misread` | `lucisv_server/src/index_cache.rs` | **rewritten**: every format `1..FACTS_FORMAT` is discarded by the header, *and* a genuine format-3 record (today's minus the two line fields) fails `decode` even served past the header. Was pinned at the literal `2` and would have gone on testing 2 forever | +| `a_closed_files_text_is_read_once_and_then_reused` | `lucisv_server/src/state.rs` | the cache exists: the file is rewritten behind the server's back and the second view is the first | +| `a_file_an_open_buffer_speaks_for_has_no_view_of_its_own` | same | closed files only | +| `every_way_a_files_text_can_move_drops_its_view` | same | all four invalidation points, each by the same warm-change-event-check experiment | +| `the_view_cache_holds_a_handful_of_files_and_a_bounded_amount_of_text` | same | both bounds, LRU order, and that a file over the whole byte budget is still cached and evicts the rest | +| `a_closed_files_heading_line_comes_from_the_index_and_not_from_a_read` | `lucisv_server/src/hover.rs` | the round's central claim: the file is deleted and the heading still names its line, snippet correctly dropped | +| `a_second_hover_into_one_closed_file_reads_nothing` | same | the snippet's read is shared: the file is rewritten and the second card is the first | + +Two `#[ignore]`d probes added (`perf::hovering_into_a_big_closed_file_first_touch_and_repeat`, +`e2e::a_hover_issued_during_the_initial_scan_waits_for_it`); one existing probe +(`hovering_into_a_large_closed_file_reads_it_once`) grew a second timing so it +reports the repeat beside the first touch. + +**Gates.** `cargo fmt --all -- --check` clean. `cargo clippy --all-targets +--workspace` silent. `cargo test --workspace` green, 0 failed. The counts, by +binary: `lucisv_server`'s unit tests **1 210 passed / 24 ignored** (+6 passing, ++1 `#[ignore]`d probe), its `e2e` suite **56 passed / 2 ignored** (+1 +`#[ignore]`d probe), `vlog_semantic`'s `workspace` suite **66 passed** (+4). +One test was renamed rather than added +(`a_store_from_the_previous_facts_format_is_dropped_not_misread` → +`a_store_from_any_previous_facts_format_is_dropped_not_misread`), so nothing +was quietly dropped. + +## QA log + +### 2026-08-28 — QA + +Verdict: **SHIP.** No correctness bug found in the round's own code — every +finding below is a test-coverage gap, closed in this pass with permanent +regression tests. All seven charter items checked; details follow. + +**1. Heading staleness — reproduced, and the documented window holds.** +Constructed the exact attack: index `sub.sv` from its original text, then +rewrite it on disk (`addr` moved from line 2 to line 6, and the byte offset +the index still holds for it now lands inside a comment) with no `didSave`, no +watcher event and no `update_one`/`rebuild_index` call — before any hover has +ever read the file, so the view cache is empty and the read the snippet does +is genuinely against the *new* bytes. Result: the heading still shows +`sub.sv:2` (the index's last-scanned line, not the file's true current one), +and the snippet is dropped by `spells_exactly` rather than showing whatever +now sits at that byte range — no wrong line and no wrong snippet, matching the +README's Assumptions ("both are stale together") exactly. Pinned: +`hover::tests::an_unreindexed_disk_edit_leaves_a_stale_heading_and_no_wrong_snippet` +(`crates/lucisv_server/src/hover.rs`). The docs (this README's Assumptions +section, and `Workspace::file_view`'s doc comment at +`crates/lucisv_server/src/state.rs:1043`) already state this honestly — no +doc fix needed. + +**2. `DeclLines` correctness — dev's tests already cover the awkward +offsets** (line 1, the last line with no trailing newline, CRLF, multi-byte +text ahead of the declaration, a split port's two lines, an ANSI port's +`None`) and check each recorded line against the source line's own text, not +just against a hand-computed expectation. No drift found; ran unmodified. + +**3. View-cache attacks — three untested-but-correct paths, now covered.** +The cache's own logic (`trim_views`, `cached_view`, +`crates/lucisv_server/src/state.rs:349` and `:1061`) was already right by +inspection and by trace, but three of the charter's named attacks had no +regression test, meaning a future refactor could break any of them silently: + - *Recency, not insertion order.* `cached_view`'s `rotate_right` had no test + at all. Added + `state::tests::re_hovering_the_oldest_cached_file_saves_it_from_eviction`: + fills the cache, re-touches the oldest entry, adds a fifth file, and + requires the just-touched file to survive while the untouched one is what + falls off instead. + - *`update_one` selectivity.* Every existing invalidation test warms one + file's view at a time, so a hypothetical `update_one` that widened to + `views.clear()` would still pass all of them. Added + `state::tests::updating_one_file_leaves_another_files_cached_view_alone`. + - *A second oversized file.* The existing bound test caches exactly one + file over the byte budget; it never tries a second one. Added + `state::tests::a_second_oversized_file_evicts_the_first_rather_than_growing_beside_it`, + confirming the cache stays at one entry (the newest) rather than + accumulating unbounded huge files. + All three pass against the round's code unmodified — genuine coverage gaps, + not bugs. + +**4. Format bump — the single-decl test's premise checked, and generalized.** +`index_cache`'s `a_store_from_any_previous_facts_format_is_dropped_not_misread` +genuinely constructs a format-3 record (verified by hand: `strip_the_line_ +fields` removes exactly the two trailing fields of the one declaration `M` +has, and the record that results is what format 3 actually wrote — not merely +a v3 header over v4 bytes). That fixture has only one declaration, so it could +not have caught a field-shift that landed on a *second* declaration's fields +rather than on a tag literal. Added +`vlog_semantic::tests::workspace::a_format_3_record_with_two_declarations_is_ +rejected_not_misread`, generalizing the stripper to N declarations (both units +and members) and covering a two-unit file and a mixed unit+split-port-member +file. Both decode to `None`, confirming the structural reason this is safe in +general: a field-shift by exactly one declaration's two line-fields always +lands either on a tag literal (`"M"`, `"I"`, …) or on the next declaration's +`name`/`kind` string fields, and a Verilog identifier can never parse as +`u32`, so `Reader::num` fails and `decode` returns `None` rather than building +a `Decl` out of someone else's fields. No misread constructed; the +"guilty until proven innocent" bar is met. + +**5. Equivalence — confirmed, not just claimed.** `cargo test --workspace` +green with 0 failures both before and after this pass's additions (dev's +counts: `lucisv_server` 1210 passed/24 ignored, `vlog_semantic` `workspace` 66 +passed — both unmodified by this pass except for the new tests below). Read +the `hover.rs` and `locate.rs` diffs directly: the live-buffer branch is +untouched, `location()`'s open-buffer arm is a straight substitution +(`doc.positions()` for the old `Positions::new(&text, &index)` built from a +clone of the same text), and the disk branch is the only place behavior can +differ — which is exactly the one documented corner (an unreadable closed +file now shows its indexed line). No other behavior change found. + +**6. Numbers reproduced**, `--release`, this machine, this session: + - `perf::hovering_into_a_big_closed_file_first_touch_and_repeat`: first + touch 5.75 ms (instantiation) / 5.65 ms (port), repeat 1.35 µs / 1.89 µs — + same order as the README's 6.23 ms / 0.95 µs and 5.92 ms / 0.99 µs; run- + to-run noise, not drift. + - `state::tests::qa_perf_cold_warm_and_half_warm_scans` (860-file corpus): + store size **2 380 790 bytes** — an exact match to the README's "after" + figure, confirming the +68 KB / 2.9 % growth claim against the real + corpus rather than trusting the doc's arithmetic. Scan times (325 / 350 / + 186 ms) were in the same band as the README's (343 / 374 / 200 ms); + machine noise, no regression. + - `e2e::a_hover_issued_during_the_initial_scan_waits_for_it`: 748.7 ms cold + / 274.0 ms warm for the first hover issued the moment `initialized` is + sent, vs. 26.3 µs / 40.2 µs once the scan is done — the same four-orders- + of-magnitude gap the README reports (780 / 287 ms vs. 64 / 61 µs). The + test genuinely exercises the wait (it asserts the answer resolves + correctly across files, and the two timings are taken across the real + wire protocol against the shipped binary) — the Handshake in this + README's "Suspect 2" section is accurate and not overstated. + +**7. Full gates**, run after adding the tests above: + - `cargo fmt --all -- --check`: clean (after formatting the new tests — + two blocks needed `cargo fmt`'s wrapping, applied). + - `cargo clippy --all-targets --workspace`: clean, no warnings. + - `cargo test --workspace`: green. `lucisv_server` unit tests **1214 + passed** (dev's 1210 + this pass's 4), `vlog_semantic` `workspace` suite + **67 passed** (dev's 66 + this pass's 1). 0 failed anywhere in the + workspace, including doctests. + - `node editors/vscode/smoke.js ./target/debug/lucisv-server`: `smoke: OK`. + +**Tests added this pass** (5, all permanent regressions, all green): +`hover::tests::an_unreindexed_disk_edit_leaves_a_stale_heading_and_no_wrong_snippet`, +`state::tests::re_hovering_the_oldest_cached_file_saves_it_from_eviction`, +`state::tests::updating_one_file_leaves_another_files_cached_view_alone`, +`state::tests::a_second_oversized_file_evicts_the_first_rather_than_growing_beside_it` +(all `crates/lucisv_server/src/`), and +`vlog_semantic::tests::workspace::a_format_3_record_with_two_declarations_is_rejected_not_misread` +(`crates/vlog_semantic/tests/workspace.rs`). + +## Review + +**2026-08-28 — lead.** Reviewed after QA's SHIP; gates re-run +independently (fmt clean, clippy silent, 2440 workspace tests green). +This round is the owner's design implemented at the right altitude: +`DeclLines` as a field on the carrier the index already had — not a +parallel table — so ports got their lines for free through the member +entries and the extension story is "add a field, bump the format", +exactly the flexibility the owner asked for. The +68 KB store growth +on the 860-file corpus scales to the owner's 20 000-module thought +experiment at the few-tens-of-KB order they predicted. The `FileView` +cache is honest about its one unwatchable staleness case and leans on +`spells_exactly` correctly (a stale view omits, never lies); QA's +staleness repro pins the heading/snippet pair going stale *together*. +The dev's rewrite of the format-discard test from a pinned literal to +all-previous-formats is the kind of fix that outlives the round. +Suspect 2 — the first request of a session waiting 287–780 ms behind +the startup scan — is confirmed genuine by dev and QA independently +and is the dominant remainder of the owner's "slow on first try"; +correctly filed as a Handshake, next round's work. Accepted; committed +by the lead. diff --git a/docs/features/index-persistence/README.md b/docs/features/index-persistence/README.md index 065c1f7..e1f9f0e 100644 --- a/docs/features/index-persistence/README.md +++ b/docs/features/index-persistence/README.md @@ -216,7 +216,18 @@ impl WorkspaceIndex { - Since indexed navigation (2026-08-27), the private facts also carry compact local/external reference records used to rebuild declaration-to-occurrence postings. That encoding change bumped `FACTS_FORMAT` from 1 to 2; no cache - migration is attempted or needed. + migration is attempted or needed. **2 → 3** (2026-08-28, + `docs/features/port-detail-spans/README.md`): each declaration gained its + `detail_span`. **3 → 4** (2026-08-28, + `docs/features/hover-line-index/README.md`): each declaration gained its two + *line numbers*, which is what lets a server print `file:line` for an indexed + declaration without reading that file. Same rule each time, same + consequence: the store is discarded whole on the first scan after the + upgrade and rewritten — measured at about 175 ms over the 860-file corpus, + once. `a_store_from_any_previous_facts_format_is_dropped_not_misread` now + checks **every** format this build is not, rather than the one literal + number it was pinned at, so the next bump inherits the test. + The store grew 68 KB (2.9 %) for the lines. - `record_path` is public separately because a store keyed by path reads that field out of every record it holds and decodes only the ones it is asked for. @@ -350,7 +361,13 @@ name span `19..20`), no members, one instantiation edge (of `sub`, owned by `m` whose name is at `19..20` and whose declaration runs `12..41`, with the site's own name span `22..25`), no subclasses, and one external reference fact (`e`, name `sub`, one resolution path also named `sub`, occurrence `22..25`), -then the checksum. The record is what lies between the hash field and the +then the checksum. **The example is written at `FACTS_FORMAT` 2 and is kept +for its shape, not its field count**: since then every declaration also +carries its detail span (`0 0` when there is none, format 3) and its two line +numbers (format 4), so a real record today has four more numbers per +declaration than the one above. The framing — one line, tab-separated, +length-prefixed lists, checksum last — is what the example is for and is +unchanged. The record is what lies between the hash field and the checksum; both hashes above are illustrative. **Any change to what a record holds or how it is written bumps diff --git a/docs/features/lucisv-server/README.md b/docs/features/lucisv-server/README.md index a368d75..4563dbb 100644 --- a/docs/features/lucisv-server/README.md +++ b/docs/features/lucisv-server/README.md @@ -28,7 +28,7 @@ looks like language knowledge in here is a bug or a `Handshake` request. | `textDocument/semanticTokens/full` | `vlog_parser::tokenize` + `Semantics` | Delta-encoded, split at line boundaries. Stamped with a `resultId` since 2026-08-26, so a delta can name it. **Declined with an error on a buffer over `lucisv.largeFile.threshold`** (2026-08-27): VS Code marks a model whose document provider answered *anything* as complete and then never asks its range provider again, so an empty answer would cost a 100 MB file all of its colour — see `docs/features/large-file-mode/README.md` | | `textDocument/semanticTokens/range` | the same classification pass | The visible lines only, for the first paint of a large file. A **self-contained** answer: the tokens overlapping the range, kept whole, re-encoded from the start of the document. No `resultId` — a partial view is not what a delta is computed against. See `docs/features/semantic-tokens-delta/README.md`. On a buffer over `lucisv.largeFile.threshold` this is the **only** request that colours anything, and it lexes the window itself (0.25 ms for a viewport of a 100 MB file) rather than filtering a token stream that was never built | | `textDocument/semanticTokens/full/delta` | the same classification pass | What changed since the answer the client names: one edit replacing everything between the common prefix and the common suffix (the suffix capped so the two cannot overlap — identical lines of Verilog encode identically, which is exactly the trap). An id the server does not hold, including one from before a `didClose`, is answered in full. Same feature README | -| `textDocument/hover` | `DefineTable`, `Semantics`, `WorkspaceIndex`, `includes::IncludeGraph`, `expand` | Macro body, or declaration kind + snippet. A macro this file does not define is answered from the workspace: the definition it **reaches through its `` `include``s** when exactly one is reachable, and every candidate otherwise. A macro card also shows what the hovered use **expands to in one step** — the body with this call's arguments substituted — when that says more than the body already does; a nested `` `INNER`` is left as written, an argument count that does not match expands nothing, and several candidates expand nothing. See `docs/features/macro-expansion/README.md`. A **cross-file** answer carries the declaration's own source line(s) under its `file:line` heading — `input logic [7:0] addr`, not just where it lives — read at hover time from the live buffer when that file is open and from disk otherwise, and omitted whenever the text and the span disagree: `docs/features/hover-declarations/README.md`. A **non-ANSI port** — named in the module header, completed in the body by `input signed [31:0] data_in;`, and likewise an old-style task or function argument — shows both places as two fenced sections, each carrying every comment that documents it (above, beside and below, where nothing else claims them): `docs/features/port-detail-spans/README.md` | +| `textDocument/hover` | `DefineTable`, `Semantics`, `WorkspaceIndex`, `includes::IncludeGraph`, `expand` | Macro body, or declaration kind + snippet. A macro this file does not define is answered from the workspace: the definition it **reaches through its `` `include``s** when exactly one is reachable, and every candidate otherwise. A macro card also shows what the hovered use **expands to in one step** — the body with this call's arguments substituted — when that says more than the body already does; a nested `` `INNER`` is left as written, an argument count that does not match expands nothing, and several candidates expand nothing. See `docs/features/macro-expansion/README.md`. A **cross-file** answer carries the declaration's own source line(s) under its `file:line` heading — `input logic [7:0] addr`, not just where it lives — read at hover time from the live buffer when that file is open and from disk otherwise, and omitted whenever the text and the span disagree: `docs/features/hover-declarations/README.md`. A **non-ANSI port** — named in the module header, completed in the body by `input signed [31:0] data_in;`, and likewise an old-style task or function argument — shows both places as two fenced sections, each carrying every comment that documents it (above, beside and below, where nothing else claims them): `docs/features/port-detail-spans/README.md`. The `file:line` half of a cross-file heading costs **no file access**: the line is recorded when the file is indexed (`Def::lines`), so only the snippet still reads, once per file per generation of it through `Workspace::file_view`: `docs/features/hover-line-index/README.md` | | `textDocument/definition` | `includes::IncludeGraph`, then `Semantics`, then `ExternalResolutions` | A cursor on an `` `include`` line jumps to the resolved file's first byte; otherwise the in-file symbol table, then the workspace overlay, whose `Ambiguous` answer returns every location. A non-ANSI port answers two locations, its body declaration first — the same two the hover card shows, in the same order (`docs/features/port-detail-spans/README.md`). See `docs/features/include-nav/README.md` | | `textDocument/typeDefinition` | `type_def`, then `nav::definition` | The same jump one token to the left: from a name to where its **type** is declared — a `typedef`, an `interface`, a `class`, or the module an instance name stands for. The tree says which declaration a position is in and where its type name is written; the answer is then `definition` of *that* name, so cross-file resolution, ambiguity and position conversion are all the ones F12 already uses. One hop on an alias chain, an empty list for a built-in. See `docs/features/type-definition/README.md` | | `textDocument/linkedEditingRange` | `linked`, over `Document.tree` | SV's closing labels, edited as one name: the cursor on either half of `module m ... endmodule : m` (and of `endfunction`/`endtask`/`endclass`/`endpackage`/`endinterface`/`endclocking`, a named `begin`/`fork`, a generate block, and the prefix-labelled `b : begin ... end : b`) answers **both** ranges plus the SV `wordPattern`. The pair comes off one AST node — `name_span` with `end_label_span` — never off a text match, so four identical names at two nesting levels still pair syntactically. Two `null`s on purpose: a closer with **no** label (nothing to co-edit, and this never offers to create one) and a **mismatched** one (the spec requires identical text; linking would silently rewrite broken code). Escaped identifiers are excluded. See `docs/features/linked-editing/README.md` | diff --git a/docs/features/workspace-index/README.md b/docs/features/workspace-index/README.md index 20b5bde..1e7d86d 100644 --- a/docs/features/workspace-index/README.md +++ b/docs/features/workspace-index/README.md @@ -44,7 +44,10 @@ impl WorkspaceIndex { fn counts(&self) -> IndexCounts; } -struct Def { file: FileId, name_span: TextRange, kind: SymbolKind } +struct Def { file: FileId, name_span: TextRange, kind: SymbolKind, + detail_span: Option, // 2026-08-28, port-detail-spans + lines: DeclLines } // 2026-08-28, hover-line-index +struct DeclLines { name: u32, detail: Option } // 1-based source lines struct WorkspaceSymbol<'a> { name: &'a str, container: Option<&'a str>, def: &'a Def } struct IndexCounts { files, modules, packages, typedefs, members, defines } @@ -275,6 +278,15 @@ unchanged by where the span comes from. Nothing here needs revisiting when order in every returned slice, regardless of iteration order. - `Def.name_span` is a non-empty byte range in `Def.file` that slices back to exactly the name that was looked up (asserted over the whole corpus). +- `Def.lines` (2026-08-28, `docs/features/hover-line-index/README.md`) is the + 1-based line each of those spans falls on, read off the same text the span + was read from, in the same pass. It is what lets a consumer print + `file:line` for an indexed declaration with no file access at all. **A line + is not text**: the index still keeps no file contents, exactly as it keeps + no contents for the spans it has always held. The field is a struct rather + than a bare number so richer per-declaration position data extends it by + gaining a field — members are `Decl`s like units are, so a module's ports + already carry their own lines here. - `resolve_external` does not mutate `Semantics` and holds no borrow of the index in its result. @@ -424,6 +436,19 @@ and more than half of all external candidates answered on clean files. ## Work log +**2026-08-28 — declaration lines** (`docs/features/hover-line-index/README.md`). +`Def` and the per-file `Decl` gained `lines: DeclLines { name, detail }`, the +1-based source lines of `name_span` and of `detail_span`, computed in +`facts_from_analysis` from a `LineIndex` over the file being indexed. +`FileFacts::from_analysis` takes that index as a parameter (its one real caller +already holds one); `FileFacts::of` builds its own. The record format grew two +fields per declaration and `FACTS_FORMAT` went **3 → 4**. +`WorkspaceIndex::fingerprint`'s `sym` line carries the lines, so the +incremental-equals-fresh witness covers them — every existing equivalence test +stayed green unmodified. Cost, measured over the corpus: the whole scan is +unchanged inside its noise (one `LineIndex::new` per parsed file, under 1 % of +that file's parse) and the persistent store grows 68 KB over 860 files, 2.9 %. + **2026-08-27 — indexed navigation.** `FileFacts` gained compact local and external reference records and its persisted format moved to version 2. `WorkspaceIndex` resolves them into reverse postings after declaration tables diff --git a/docs/perf/README.md b/docs/perf/README.md index aa7cc40..6f2d69e 100644 --- a/docs/perf/README.md +++ b/docs/perf/README.md @@ -264,11 +264,63 @@ touched this round, so the flush table above is a baseline rather than an after. The reasons each candidate was refused, with its number, are in the next section. +## Before / after — round 3 (2026-08-28) + +`docs/features/hover-line-index/README.md` — the owner's report that hovering +an instantiation, and a port on that instantiation, is slow on the first try. +Two suspects were measured before anything was changed; the numbers said which +one this round could fix and which it could only file. + +**D1 — the heading stopped reading the file, and the snippet's read is +shared.** Each indexed declaration now carries its line (`Def::lines`, +`FACTS_FORMAT` 3 → 4), so `file:line` costs nothing; the snippet still wants +that file's text, and takes it from a four-entry / 8 MiB LRU of closed files' +text in `Workspace`. So the *first* touch of a file still pays one read and +every touch after it pays nothing. + +| | before | after | +|---|---:|---:| +| hover on an instantiation into a 12 MB closed file, first touch | 6.47 ms | 6.23 ms | +| — the same hover again | 5.75 ms | **0.95 µs** | +| hover on a port into the same file, first touch | 5.85 ms | 5.92 ms | +| — the same hover again | 5.71 ms | **0.99 µs** | +| the 31.7 MB probe above, first touch | 17.0 ms | 16.8 ms | +| — the same hover again | 17.0 ms | **4.4 µs** | +| `perf::hovering_across_files_into_a_closed_file`, 1k / 10k (mean of 20) | 39.8 / 157 µs | **4.7 / 12.9 µs** | + +The cost, over the 860-file corpus: one `LineIndex::new` per parsed file, which +leaves every scan figure inside its own noise (no cache 338 → 343 ms, cold +372 → 374 ms, warm 197 → 200 ms), and 68 KB more store — 2.9 %. + +**D2 — the first request of a session waits out the startup scan. +Measured, filed, not fixed.** `Server::new` runs the whole scan before the +message loop takes its first message, so anything a client sends the instant +the handshake finishes sits in the OS pipe until the scan ends. Over 200 files +of 1 000 lines, through the shipped binary +(`tests/e2e.rs::a_hover_issued_during_the_initial_scan_waits_for_it`): + +| the first hover of a session | cold store | warm store | +|---|---:|---:| +| issued the moment `initialized` was sent | **780 ms** | **287 ms** | +| the same hover once the scan is done | 64 µs | 61 µs | + +This is four orders of magnitude larger than D1 and is where "the first hover +is slow" mostly lives. Fixing it is a change to request scheduling — answering +while the index is half-built, or scanning off the message-loop thread — and +was explicitly out of this round's scope. + ## What it would take to go faster Ranked by what the measurements above say is there, with what each would cost. None of these were attempted; each is a future round. +0. **Answer requests during the startup scan — 780 ms cold, 287 ms warm, on + the first request of a session.** New in round 3's measurements (D2 above) + and the largest single number on this page. It is not a code-speed problem: + the work is already as fast as the persistent cache can make it, and what + costs the user is that the message loop has not started yet. Any fix is a + change to what an answer *means* while the index is half-built, so it needs + a design round, not an optimisation. 1. **Incremental lexing and parsing — 24.5 ms of a 31 ms flush at 10 000 lines (79 %).** This is the only large lever left. It is also the one change that runs straight into `CLAUDE.md`'s hard invariants 1 and 2: the @@ -318,6 +370,13 @@ cost. None of these were attempted; each is a future round. - [x] **Added in round 2:** one flush stage by stage, including the `diagnostics::all` pass that runs on every publish and that round 1's table did not account for. +- [x] **Added in round 3 (2026-08-28):** a hover into a big closed file with + the **first touch and the repeat reported separately** + (`perf::hovering_into_a_big_closed_file_first_touch_and_repeat`) — every + earlier hover probe reported a mean, which hides exactly the split the + owner's report was about — and the first request of a session against + the shipped binary, with a cold store and a warm one + (`tests/e2e.rs::a_hover_issued_during_the_initial_scan_waits_for_it`). `perf::breaking_down_one_flushed_keystroke`. - [ ] **Round 1's second open TODO, restated and still open:** memory. Nothing in the repo measures resident size. Round 2 added no data