From 651e58bfb398dfa7a1b16096e9d05f5315d037b7 Mon Sep 17 00:00:00 2001 From: Guoliang Chen Date: Sat, 29 Aug 2026 03:39:06 -0700 Subject: [PATCH] The design-hierarchy sidebar: codex's feature, integrated MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An instance-oriented hierarchy view in the Activity Bar — lucisv/moduleHierarchy snapshots (schema 2: uri table, flat ranges, derived ids; 11.6 MB -> 2.3 MB on opentitan) plus lucisv/moduleHierarchyChanged invalidation, gated on the extension's initializationOptions. Format 5 carries decl spans, instance occurrences and client positions for file-scope declarations (+1.7-1.9 % store), so a snapshot reads no files at all: handler 145-167 -> 17-20 ms settled, a save with the sidebar open 366 -> 141 ms. complete is !scanning && !must_wait, pinned. Owner UI rounds: no hover preview, all levels collapsed by default with stable ids across refreshes, and search over a resident flat model (freeze diagnosed: materialized expanded tree x undebounced double fuzzyScore x whole-tree clone per keystroke) — prebuilt lowercased index, bitmask prefilter, top-K counting, 200-row cap with an honest remainder, single-digit ms over a 120k-entry fixture. LineIndex::utf16_position unifies the index's and the wire's position math under a cross-crate agreement test. Implementation: codex. Integration fixes + owner items: Opus dev. QA: lead (measurement pass) + Sonnet (SHIP, independent oracles). Co-Authored-By: Claude Fable 5 --- TODO.md | 39 + crates/lucisv_server/src/convert.rs | 14 +- crates/lucisv_server/src/design_hierarchy.rs | 500 +++++++++++ crates/lucisv_server/src/index_cache.rs | 51 +- crates/lucisv_server/src/main.rs | 33 +- crates/lucisv_server/src/server.rs | 151 +++- crates/lucisv_server/src/state.rs | 9 +- crates/vlog_parser/src/line_index.rs | 62 ++ crates/vlog_semantic/src/facts.rs | 75 +- crates/vlog_semantic/src/lib.rs | 7 +- crates/vlog_semantic/src/workspace.rs | 172 +++- crates/vlog_semantic/tests/workspace.rs | 159 +++- docs/features/hover-line-index/README.md | 10 +- docs/features/index-persistence/README.md | 32 +- .../vscode-hierarchy-sidebar/README.md | 806 ++++++++++++++++++ docs/features/workspace-index/README.md | 15 +- editors/vscode/.vscodeignore | 2 + editors/vscode/CHANGELOG.md | 20 + editors/vscode/README.md | 4 + editors/vscode/extension.js | 14 +- editors/vscode/hierarchyModel.js | 574 +++++++++++++ editors/vscode/hierarchyModel_test.js | 409 +++++++++ editors/vscode/hierarchyView.js | 276 ++++++ editors/vscode/hierarchyView_test.js | 190 +++++ editors/vscode/images/hierarchy.svg | 6 + editors/vscode/media/hierarchy.css | 85 ++ editors/vscode/media/hierarchy.js | 192 +++++ editors/vscode/package.json | 47 +- editors/vscode/smoke.js | 18 + topo.md | 6 + 30 files changed, 3891 insertions(+), 87 deletions(-) create mode 100644 crates/lucisv_server/src/design_hierarchy.rs create mode 100644 docs/features/vscode-hierarchy-sidebar/README.md create mode 100644 editors/vscode/hierarchyModel.js create mode 100644 editors/vscode/hierarchyModel_test.js create mode 100644 editors/vscode/hierarchyView.js create mode 100644 editors/vscode/hierarchyView_test.js create mode 100644 editors/vscode/images/hierarchy.svg create mode 100644 editors/vscode/media/hierarchy.css create mode 100644 editors/vscode/media/hierarchy.js diff --git a/TODO.md b/TODO.md index 433899c..e193341 100644 --- a/TODO.md +++ b/TODO.md @@ -1218,3 +1218,42 @@ references-nav,index-scope}/README.md, docs/perf/README.md) (rung 6, `files_spelling`); the macro-invocation warning loss is accepted as documented, with the `FileFacts` macro census filed as the real fix. + +## VS Code design-hierarchy sidebar (2026-08-29) + +Feature by codex; this section is that round plus the lead's QA finding +and three owner items. See +`docs/features/vscode-hierarchy-sidebar/README.md`. + +- [x] `lucisv/moduleHierarchy` + `lucisv/moduleHierarchyChanged`, gated + on `initializationOptions.hierarchyView`; Activity Bar container, + webview view, navigation, context menu, bookmark. +- [x] `FACTS_FORMAT` 4 → 5: `Def::decl_span`, per-instance + `InstanceOccurrence`s on the statement edge, and client positions + on file-scope declarations and instance occurrences. Call + hierarchy and code-lens counts unchanged. +- [x] **Lead's HIGH finding — the snapshot read every module-declaring + file per request.** Fixed by index-carried positions (zero file + I/O), `WorkspaceIndex::units_of`, and a schema-2 wire (file + table, four-number ranges, no ids, no per-instance definition + copies). On opentitan, server-side handler **145–167 ms → 17–20 ms** + warm, response **11.6 MB → 2.3 MB**, a definition pipelined behind + a snapshot **263 ms → 41 ms**. Store cost of the positions: +1.7 % + on the corpus, +1.9 % on opentitan. +- [x] `complete` tightened to `!scanning && !must_wait()` and the + window it has to be honest about written down and tested. +- [x] Owner: the five-line hover source preview removed — the feature's + last consumer of file text. +- [x] Owner: every tree level collapsed by default; expansion state + survives a refresh on stable row ids. +- [x] Owner: search freeze fixed. The model is flat and resident, tree + levels are built lazily, and a query is one pass over a prebuilt + lowercased index with a character-mask pre-filter and a counting + top-K — 3–8 ms per query over a generated 120 000-entry + hierarchy, asserted in the node suite. +- [ ] Filed, not done: rewire `locate::location` onto `DeclPositions` + so `textDocument/definition`, references, the lens and both + hierarchies stop reading a file to convert an indexed span. Every + unit's range is now in the index for free. +- [ ] Manual extension-host acceptance (themes, keyboard-only, zoom, + screen readers, an old server binary, both VSIX shapes). diff --git a/crates/lucisv_server/src/convert.rs b/crates/lucisv_server/src/convert.rs index cdf01be..628d3f1 100644 --- a/crates/lucisv_server/src/convert.rs +++ b/crates/lucisv_server/src/convert.rs @@ -24,15 +24,13 @@ impl<'a> Positions<'a> { /// The LSP position of a byte offset. An offset inside a multi-byte /// character is floored to that character's start. + /// + /// The conversion itself lives on [`LineIndex`], so that the semantic + /// index — which records the same positions for a declaration while its + /// file is scanned — cannot answer differently from the wire. pub fn position(&self, offset: u32) -> Position { - let offset = self.floor_boundary(offset); - let (line, _) = self.index.line_col(offset); - let start = self.index.line_range(line).map_or(0, |r| r.start) as usize; - let slice = self.text.get(start..offset as usize).unwrap_or(""); - // LSP line content excludes the whole `\r\n`; `LineIndex` keeps the - // `\r` as an ordinary byte of its line, so drop it here. - let slice = slice.strip_suffix('\r').unwrap_or(slice); - Position { line: line - 1, character: utf16_len(slice) } + let (line, character) = self.index.utf16_position(self.text, offset); + Position { line, character } } /// A cursor for converting many byte offsets in one non-decreasing sweep, diff --git a/crates/lucisv_server/src/design_hierarchy.rs b/crates/lucisv_server/src/design_hierarchy.rs new file mode 100644 index 0000000..944f5e1 --- /dev/null +++ b/crates/lucisv_server/src/design_hierarchy.rs @@ -0,0 +1,500 @@ +//! The VS Code instance-oriented design hierarchy. +//! +//! LSP call hierarchy deliberately groups a module's calls by target module +//! type. The sidebar needs the other view of the same facts: every individual +//! instance name, its source range, and every declaration its module type may +//! name. The response stays flat; the client chooses roots and expands paths, +//! which keeps recursion out of the protocol and lets one snapshot serve +//! search as well as rendering. +//! +//! **Two things this answer must not be, and the shape follows from both.** It +//! must not read files — every line and character below was converted once, +//! when the declaring file was scanned, and rides the index +//! (`vlog_semantic::DeclPositions`, `InstanceOccurrence::positions`). And it +//! must not be enormous: a whole design re-sent on every save is a message the +//! request queue is blocked writing. So a URI is written **once**, in `files`, +//! and every location names it by index; a range is four numbers rather than +//! four nested objects; a row carries no id, because the client can compose the +//! one it used to be sent; and an instance carries no copy of the declarations +//! its module name resolves to, because the client already has every module. +//! Those four together are 11.6 MB → 1.9 MB on opentitan, and the client +//! rebuilds the richer shape in `hierarchyModel.js`'s `validateSnapshot` — see +//! `docs/features/vscode-hierarchy-sidebar/README.md`. + +use std::collections::HashMap; + +use serde::Serialize; +use vlog_semantic::{FileId, SymbolKind, Utf16Range, WorkspaceIndex}; + +use crate::state::Workspace; +use crate::uri::path_to_uri; + +pub const METHOD: &str = "lucisv/moduleHierarchy"; +pub const CHANGED_METHOD: &str = "lucisv/moduleHierarchyChanged"; + +/// The wire version. Bumped on any change to the shape below; the client +/// refuses a snapshot it does not recognise rather than half-reading one. +const SCHEMA_VERSION: u32 = 2; + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Snapshot { + schema_version: u32, + revision: u64, + complete: bool, + /// Every file a location below names, once. Locations index into this. + files: Vec, + modules: Vec, +} + +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +struct Module { + module_name: String, + definition: Location, + instances: Vec, +} + +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +struct Instance { + instance_name: String, + module_name: String, + site: Location, +} + +/// A place in the workspace: which file, the whole construct, and the name +/// inside it. Each range is `[startLine, startCharacter, endLine, +/// endCharacter]`, 0-based lines and UTF-16 characters — an LSP `Range` with +/// its four field names left off. +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +struct Location { + file: u32, + range: [u32; 4], + selection_range: [u32; 4], +} + +/// A complete snapshot of the index currently installed in `workspace`. +/// +/// **It reads no files.** The first shape of this function read every +/// module-declaring file and built a `LineIndex` over each — 5.0 s cold and +/// ~300 ms warm on opentitan, on *every* request, which is the per-request +/// whole-workspace read the release before it existed to kill. +/// +/// `complete` is false only when the request arrived between two files of the +/// startup scan. The server sends `CHANGED_METHOD` when that scan lands, so a +/// client can render the partial answer as loading and replace it once. +pub fn snapshot(workspace: &Workspace, revision: u64, complete: bool) -> Snapshot { + let index = workspace.index(); + let mut files = FileTable::default(); + + let mut modules = Vec::new(); + let mut module_at = HashMap::new(); + for (name, def) in index.units_of(SymbolKind::Module) { + // Every file-scope declaration carries its positions; one without them + // would be a declaration the index built by some other route, and + // dropping it beats inventing a range for it. + let Some(positions) = def.lines.positions else { continue }; + let Some(file) = files.of(index, def.file) else { continue }; + module_at.insert((def.file, def.name_span.start, def.name_span.end), modules.len()); + modules.push(Module { + module_name: name.to_string(), + definition: location(file, positions.name, positions.decl), + instances: Vec::new(), + }); + } + + for (target_name, edges) in index.instantiations() { + for edge in edges { + let owner = (edge.file, edge.owner.name_span.start, edge.owner.name_span.end); + let Some(&owner_at) = module_at.get(&owner) else { continue }; + let Some(file) = files.of(index, edge.file) else { continue }; + for occurrence in &edge.instances { + modules[owner_at].instances.push(Instance { + instance_name: occurrence.name.clone(), + module_name: target_name.to_string(), + site: location(file, occurrence.name_positions, occurrence.positions), + }); + } + } + } + + // `sort_by_cached_key`, not `sort_by`: both keys lowercase a name, and + // paying for that once per element rather than twice per comparison is the + // difference between a few and a few hundred thousand allocations on a + // workspace with 14 000 instances in it. + for module in &mut modules { + module.instances.sort_by_cached_key(|instance| instance_key(&files, instance)); + } + modules.sort_by_cached_key(|module| module_key(&files, module)); + + Snapshot { schema_version: SCHEMA_VERSION, revision, complete, files: files.uris, modules } +} + +/// The snapshot's file table: one URI per file, given an index the first time +/// a location needs it. +#[derive(Default)] +struct FileTable { + uris: Vec, + at: HashMap>, +} + +impl FileTable { + /// This file's index, adding it if it is new. `None` for a path that is + /// not a URI — the same answer every other feature gives for such a path, + /// and it drops that file's rows rather than the whole snapshot. + fn of(&mut self, index: &WorkspaceIndex, file: FileId) -> Option { + if let Some(&known) = self.at.get(&file) { + return known; + } + let found = index.path(file).and_then(path_to_uri).map(|uri| { + self.uris.push(uri.as_str().to_string()); + self.uris.len() as u32 - 1 + }); + self.at.insert(file, found); + found + } + + fn uri(&self, file: u32) -> &str { + self.uris.get(file as usize).map_or("", |uri| uri.as_str()) + } +} + +/// One location, built from ranges the index already holds. +fn location(file: u32, selection: Utf16Range, whole: Utf16Range) -> Location { + Location { file, range: range(whole), selection_range: range(selection) } +} + +fn range(range: Utf16Range) -> [u32; 4] { + [range.start.line, range.start.character, range.end.line, range.end.character] +} + +fn module_key(files: &FileTable, module: &Module) -> (String, String, u32, u32) { + ( + module.module_name.to_ascii_lowercase(), + files.uri(module.definition.file).to_string(), + module.definition.selection_range[0], + module.definition.selection_range[1], + ) +} + +fn instance_key(files: &FileTable, instance: &Instance) -> (String, String, String, u32, u32) { + ( + instance.instance_name.to_ascii_lowercase(), + instance.module_name.to_ascii_lowercase(), + files.uri(instance.site.file).to_string(), + instance.site.selection_range[0], + instance.site.selection_range[1], + ) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::{json, Value}; + use std::path::PathBuf; + + struct Tree(PathBuf); + + impl Tree { + fn new(name: &str) -> Tree { + let path = std::env::temp_dir() + .join(format!("lucisv_design_hierarchy_{}_{name}", std::process::id())); + let _ = std::fs::remove_dir_all(&path); + std::fs::create_dir_all(&path).expect("temp dir"); + Tree(path) + } + + fn write(&self, name: &str, text: &str) { + std::fs::write(self.0.join(name), text).expect("write fixture"); + } + + fn workspace(&self) -> Workspace { + let mut workspace = Workspace::default(); + workspace.open_whole_workspace(vec![self.0.clone()]); + workspace + } + } + + impl Drop for Tree { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + fn taken(workspace: &Workspace) -> Value { + serde_json::to_value(snapshot(workspace, 7, true)).expect("serializes") + } + + #[test] + fn a_snapshot_is_flat_sorted_and_keeps_every_individual_instance() { + let tree = Tree::new("flat"); + tree.write("leaf.sv", "module leaf; endmodule\n"); + tree.write("top.sv", "module top;\n leaf zed (), alpha ();\nendmodule\n"); + tree.write("tb.sv", "module TB; top dut (); missing u_missing (); endmodule\n"); + + let value = taken(&tree.workspace()); + assert_eq!(value["schemaVersion"], 2); + assert_eq!(value["revision"], 7); + assert_eq!(value["complete"], true); + let modules = value["modules"].as_array().expect("modules"); + let names: Vec<&str> = + modules.iter().map(|module| module["moduleName"].as_str().expect("name")).collect(); + assert_eq!(names, ["leaf", "TB", "top"], "case-insensitive alphabetical order"); + + let top = module(modules, "top"); + // `[startLine, startCharacter, endLine, endCharacter]`: the whole + // module for `range`, its name alone for `selectionRange`. + assert_eq!(top["definition"]["range"], json!([0, 0, 2, 9])); + assert_eq!(top["definition"]["selectionRange"], json!([0, 7, 0, 10])); + let instances = top["instances"].as_array().expect("instances"); + let names: Vec<&str> = instances + .iter() + .map(|instance| instance["instanceName"].as_str().expect("name")) + .collect(); + assert_eq!(names, ["alpha", "zed"], "one statement became two sorted children"); + + let tb = module(modules, "TB"); + let missing = tb["instances"] + .as_array() + .expect("instances") + .iter() + .find(|instance| instance["instanceName"] == "u_missing") + .expect("unresolved instance is still a row"); + // Nothing on the wire says "unresolved": the client asks its own module + // table for `missing`, finds none, and that is the same answer. + assert_eq!(missing["moduleName"], "missing"); + assert_eq!(missing["site"]["selectionRange"][0], 0); + } + + /// The round's central claim, pinned the way `hover-line-index` pinned its + /// own: delete every source file after indexing, and the answer is + /// byte-identical, because no part of it comes from a file. + #[test] + fn a_snapshot_reads_no_files_at_all() { + let tree = Tree::new("noreads"); + tree.write("leaf.sv", "module leaf; endmodule\n"); + tree.write("top.sv", "module top;\n leaf u_leaf ();\nendmodule\n"); + let workspace = tree.workspace(); + let before = taken(&workspace); + assert_eq!( + before["modules"].as_array().expect("modules").len(), + 2, + "premise: both indexed" + ); + + for name in ["leaf.sv", "top.sv"] { + std::fs::remove_file(tree.0.join(name)).expect("delete"); + } + assert_eq!(taken(&workspace), before, "the snapshot came from the index, not the disk"); + } + + /// A URI appears once however many rows name it, and a range is four + /// numbers — the two decisions that took the opentitan answer from 11.6 MB + /// to under 2 MB. + #[test] + fn every_file_is_named_once_and_a_range_is_four_numbers() { + let tree = Tree::new("filetable"); + tree.write("leaf.sv", "module leaf; endmodule\n"); + tree.write("top.sv", "module top;\n leaf a (), b (), c ();\nendmodule\n"); + + let value = taken(&tree.workspace()); + let files = value["files"].as_array().expect("files"); + assert_eq!(files.len(), 2, "one entry per file, not one per row: {files:#?}"); + let text = serde_json::to_string(&value).expect("serializes"); + for uri in files { + let uri = uri.as_str().expect("a uri string"); + assert_eq!(text.matches(uri).count(), 1, "{uri} is written more than once"); + } + let top = module(value["modules"].as_array().expect("modules"), "top"); + for instance in top["instances"].as_array().expect("instances") { + assert!(instance["site"]["file"].is_number(), "a file index, not a URI"); + assert_eq!(instance["site"]["range"].as_array().expect("range").len(), 4); + } + } + + /// Positions are the client's, not the index's: 0-based lines and UTF-16 + /// code units, so a two-byte character before a name still counts one. + #[test] + fn positions_are_zero_based_utf16_even_through_multibyte_text() { + let tree = Tree::new("utf16"); + // `🎉` is four UTF-8 bytes and two UTF-16 units, so every column after + // it on that line differs from the byte column the index records. + tree.write("m.sv", "module top;\n /*\u{1F389}*/ sub u_x ();\nendmodule\n"); + + let value = taken(&tree.workspace()); + let top = module(value["modules"].as_array().expect("modules"), "top"); + assert_eq!( + top["definition"]["selectionRange"], + json!([0, 7, 0, 10]), + "line 0 counting from 0, `top` at character 7" + ); + let instance = &top["instances"].as_array().expect("instances")[0]; + assert_eq!(instance["instanceName"], "u_x"); + assert_eq!(instance["site"]["selectionRange"], json!([1, 13, 1, 16])); + assert_eq!(instance["site"]["range"], json!([1, 13, 1, 19])); + } + + /// **The one property the whole zero-I/O trick rests on**: a position the + /// index recorded while a file was scanned is the position `convert` would + /// have produced from that file's text on the wire. The two answers come + /// from one function on `LineIndex`, and this is what says so out loud — + /// over the shapes that break naive conversions. + #[test] + fn an_indexed_position_is_the_position_the_wire_converter_would_have_given() { + let sources = [ + "module plain;\n sub u ();\nendmodule\n", + // A CRLF file: `\r` is a byte of its line but not of its content. + "module crlf;\r\n sub u_crlf ();\r\nendmodule\r\n", + // Two, three and four byte characters ahead of the names. + "// \u{e9}\u{2713}\u{1F389}\nmodule wide;\n /*\u{1F389}*/ sub u_wide ();\nendmodule\n", + // A name on the last line, with no trailing newline at all. + "module tail;\n sub u_tail ();\nendmodule", + // Two instances in one statement, and an attribute before `module`. + "(* keep *) module many;\n sub a (), b ();\nendmodule\n", + // CRLF and bare LF mixed in one file: the `\r`-stripping rule must + // apply per line, not once for the whole file. + "module mixed;\r\n sub u_a ();\n sub u_b ();\r\nendmodule\n", + // The instance on the very same line as the module header, so the + // name and the instance share a line's worth of UTF-16 columns. + "module oneline; sub u_same ();\nendmodule\n", + ]; + let tree = Tree::new("agreement"); + let mut texts = Vec::new(); + for (at, source) in sources.iter().enumerate() { + tree.write(&format!("f{at}.sv"), source); + texts.push((tree.0.join(format!("f{at}.sv")), *source)); + } + let workspace = tree.workspace(); + let index = workspace.index(); + + let mut checked = 0usize; + for (path, text) in &texts { + let lines = vlog_parser::LineIndex::new(text); + let positions = crate::convert::Positions::new(text, &lines); + let file = index.file_id(path).expect("the file is indexed"); + for (_, def) in index.units_of(vlog_semantic::SymbolKind::Module) { + if def.file != file { + continue; + } + let recorded = def.lines.positions.expect("a unit carries positions"); + assert_eq!(range(recorded.name), as_four(positions.range(def.name_span))); + assert_eq!(range(recorded.decl), as_four(positions.range(def.decl_span))); + checked += 1; + } + for (_, edges) in index.instantiations() { + for edge in edges.iter().filter(|edge| edge.file == file) { + for occurrence in &edge.instances { + assert_eq!( + range(occurrence.name_positions), + as_four(positions.range(occurrence.name_span)) + ); + assert_eq!( + range(occurrence.positions), + as_four(positions.range(occurrence.span)) + ); + checked += 1; + } + } + } + } + assert!(checked >= 16, "premise: every fixture contributed rows, got {checked}"); + } + + /// QA (2026-08-29): two files declaring the same module name must each + /// keep their own row, their own instances, and never merge — the wire's + /// only handle on a module is `(file, definition range)`, exactly as an + /// ambiguous type is meant to look on the client. + #[test] + fn duplicate_module_names_across_files_stay_two_distinct_rows() { + let tree = Tree::new("duplicate"); + tree.write("a.sv", "module dup;\n sub u_in_a ();\nendmodule\n"); + tree.write("b.sv", "module dup;\n sub u_in_b ();\nendmodule\n"); + tree.write("sub.sv", "module sub; endmodule\n"); + + let value = taken(&tree.workspace()); + let modules = value["modules"].as_array().expect("modules"); + let dups: Vec<&Value> = + modules.iter().filter(|module| module["moduleName"] == "dup").collect(); + assert_eq!(dups.len(), 2, "one row per declaration, not one merged row: {dups:#?}"); + assert_ne!( + dups[0]["definition"]["file"], dups[1]["definition"]["file"], + "the only thing distinguishing them is which file", + ); + let mut instance_names: Vec<&str> = dups + .iter() + .flat_map(|module| module["instances"].as_array().expect("instances")) + .map(|instance| instance["instanceName"].as_str().expect("name")) + .collect(); + instance_names.sort_unstable(); + assert_eq!( + instance_names, + ["u_in_a", "u_in_b"], + "each declaration keeps only the instances its own body writes", + ); + } + + /// QA (2026-08-29): an escaped Verilog identifier (`\foo$bar `, terminated + /// by whitespace, the space itself not part of the name) is as ordinary a + /// module or instance name as any other — the wire and the position + /// conversion must not choke on the backslash or the trailing space. + #[test] + fn an_escaped_identifier_names_a_module_and_an_instance() { + let tree = Tree::new("escaped"); + tree.write( + "m.sv", + "module \\weird$leaf ;\nendmodule\n\ + module top;\n \\weird$leaf \\u$inst ();\nendmodule\n", + ); + + let value = taken(&tree.workspace()); + let modules = value["modules"].as_array().expect("modules"); + let leaf = module(modules, "\\weird$leaf"); + assert_eq!(leaf["instances"].as_array().expect("instances").len(), 0); + let top = module(modules, "top"); + let instances = top["instances"].as_array().expect("instances"); + assert_eq!(instances.len(), 1); + assert_eq!(instances[0]["instanceName"], "\\u$inst"); + assert_eq!(instances[0]["moduleName"], "\\weird$leaf"); + } + + /// QA (2026-08-29): a module instantiated 100 times in one statement list + /// produces 100 individual, individually sorted instance rows — the + /// flattening the sidebar exists for, at a scale one instance would not + /// exercise. + #[test] + fn one_hundred_instances_of_one_module_are_one_hundred_sorted_rows() { + let tree = Tree::new("manyinstances"); + tree.write("leaf.sv", "module leaf; endmodule\n"); + let instances: Vec = (0..100).map(|n| format!("u_{n:03} ()", n = n)).collect(); + tree.write( + "top.sv", + &format!("module top;\n leaf {};\nendmodule\n", instances.join(", ")), + ); + + let value = taken(&tree.workspace()); + let top = module(value["modules"].as_array().expect("modules"), "top"); + let instances = top["instances"].as_array().expect("instances"); + assert_eq!(instances.len(), 100, "every one of the 100 instances is its own row"); + let names: Vec<&str> = instances + .iter() + .map(|instance| instance["instanceName"].as_str().expect("name")) + .collect(); + let mut sorted = names.clone(); + sorted.sort_unstable(); + assert_eq!(names, sorted, "sorted by instance name, as every module's instances are"); + assert!(instances.iter().all(|instance| instance["moduleName"] == "leaf")); + } + + fn as_four(range: lsp_types::Range) -> [u32; 4] { + [range.start.line, range.start.character, range.end.line, range.end.character] + } + + fn module<'a>(modules: &'a [Value], name: &str) -> &'a Value { + modules + .iter() + .find(|module| module["moduleName"] == name) + .unwrap_or_else(|| panic!("no module {name}: {modules:#?}")) + } +} diff --git a/crates/lucisv_server/src/index_cache.rs b/crates/lucisv_server/src/index_cache.rs index 93db63b..bd4cc18 100644 --- a/crates/lucisv_server/src/index_cache.rs +++ b/crates/lucisv_server/src/index_cache.rs @@ -594,16 +594,17 @@ mod tests { } // 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"); + // format — this one is a format-4 record, which is today's minus every + // field `vscode-hierarchy-sidebar` 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 previous = as_a_format_4_record(&encoded); + assert_ne!(previous, encoded, "premise: the fixture has fields to strip"); assert!( - FileFacts::decode(&format_3).is_none(), - "a format-3 record decoded as a format-4 one: {format_3}" + FileFacts::decode(&previous).is_none(), + "a format-{} record decoded as a format-{FACTS_FORMAT} one: {previous}", + FACTS_FORMAT - 1 ); // Finally, the store is replaced under this build's header rather than @@ -621,20 +622,32 @@ 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 { + /// Today's encoded record, minus everything `FACTS_FORMAT` 5 added — i.e. + /// exactly what format 4 wrote for the same file. Three additions and all + /// three come out: a declaration's `decl_span`, a file-scope declaration's + /// client positions, and an instantiation's per-instance occurrences. + /// + /// `M` declares exactly one unit, no members, and one instantiation of one + /// instance, so every group's field index can be computed rather than + /// parsed. Highest index first, so removing one strip does not move the + /// others. + fn as_a_format_4_record(encoded: &str) -> String { let mut fields: Vec<&str> = encoded.split('\t').collect(); + let Some(instantiations) = fields.iter().position(|f| *f == "I") else { + return encoded.to_string(); + }; + // I, count, module, owner (name + two ranges), site range — ten + // fields, then the occurrence count and its one thirteen-field + // occurrence. + fields.drain(instantiations + 10..instantiations + 10 + 1 + 13); 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); - } + // U, count, then name, kind, name_span×2, decl_span×2, detail×2, + // lines×2, and the unit's two client ranges — four numbers each. + let decl_at = units + 2; + fields.drain(decl_at + 10..decl_at + 18); + fields.drain(decl_at + 4..decl_at + 6); fields.join("\t") } diff --git a/crates/lucisv_server/src/main.rs b/crates/lucisv_server/src/main.rs index a5ce863..76e518c 100644 --- a/crates/lucisv_server/src/main.rs +++ b/crates/lucisv_server/src/main.rs @@ -10,6 +10,7 @@ mod candidates; mod code_action; mod completion; mod convert; +mod design_hierarchy; mod diagnostics; mod expand; mod file_ops; @@ -73,10 +74,14 @@ use crate::uri::uri_to_path; /// log channel. One spelling, no `-v` — see /// `docs/features/verbose-timing/README.md`. const VERBOSE: &str = "--verbose"; +/// `vscode-languageclient` appends `--stdio` for TransportKind.stdio — the +/// only transport this server has. Accepted as a no-op (lead hotfix +/// 2026-08-29, mirrored from master e440798; will merge cleanly). +const STDIO: &str = "--stdio"; /// What someone who spelled an argument wrong is told, on stderr. One line: /// this binary is spawned by an editor, not typed at a prompt. -const USAGE: &str = "usage: lucisv-server [--verbose]"; +const USAGE: &str = "usage: lucisv-server [--verbose] [--stdio]"; fn main() -> Result<(), Box> { // Before the transport: an argument we do not understand means the client @@ -101,6 +106,7 @@ fn main() -> Result<(), Box> { // capability at all: `initializationOptions` is whatever the client's // extension put there. let storage = storage_path(¶ms); + let hierarchy_view = hierarchy_view_support(¶ms); // A client that sends params we cannot read still gets a server; every // field we want is optional anyway. let params: InitializeParams = serde_json::from_value(params).unwrap_or_default(); @@ -115,6 +121,7 @@ fn main() -> Result<(), Box> { show_document: show_document_support(¶ms), configuration: configuration_support(¶ms), token_server_cancel: token_server_cancel_support(¶ms), + hierarchy_view, }; connection.initialize_finish(id, initialize_value(ranges_formatting)?)?; @@ -146,6 +153,9 @@ fn main() -> Result<(), Box> { fn verbose_flag(args: impl Iterator) -> Result { let mut verbose = false; for arg in args { + if arg == STDIO { + continue; + } if arg != VERBOSE { return Err(arg); } @@ -451,6 +461,13 @@ fn storage_path(params: &serde_json::Value) -> Option { (!path.trim().is_empty()).then(|| PathBuf::from(path)) } +/// Whether this client hosts lucisv's custom hierarchy view and therefore +/// wants invalidation notifications for it. The snapshot request itself is +/// always served; this gate prevents unsolicited traffic to other LSP clients. +fn hierarchy_view_support(params: &serde_json::Value) -> bool { + params["initializationOptions"]["hierarchyView"] == true +} + /// Whether the client can expand `${1:x}` tabstops in a completion item. /// /// A client that did not say so gets the skeleton as plain text: a literal @@ -822,6 +839,20 @@ mod tests { assert!(!ranges_formatting_support(&serde_json::Value::Null)); } + #[test] + fn hierarchy_notifications_are_an_explicit_initialization_option() { + let saying = serde_json::json!({ "initializationOptions": { "hierarchyView": true } }); + assert!(hierarchy_view_support(&saying)); + for silent in [ + serde_json::json!({}), + serde_json::json!({ "initializationOptions": { "hierarchyView": false } }), + serde_json::json!({ "initializationOptions": { "hierarchyView": "yes" } }), + serde_json::Value::Null, + ] { + assert!(!hierarchy_view_support(&silent), "{silent:#?}"); + } + } + #[test] fn a_client_that_did_not_ask_sees_the_capability_exactly_as_it_always_was() { // The gate's whole point: every client that shipped before this round diff --git a/crates/lucisv_server/src/server.rs b/crates/lucisv_server/src/server.rs index 427e7df..07b3ca8 100644 --- a/crates/lucisv_server/src/server.rs +++ b/crates/lucisv_server/src/server.rs @@ -68,9 +68,9 @@ use serde_json::Value; use crate::settings::ClientSettings; use crate::state::{IndexEvent, Scan, Workspace}; use crate::{ - code_action, completion, diagnostics, file_ops, folding, format, hierarchy, hover, includes, - inlay, inline, large, lens, linked, nav, on_type, pairs, ports, rename, selection, settings, - signature, symbols, sync, tokens, type_def, type_hierarchy, watch, + code_action, completion, design_hierarchy, diagnostics, file_ops, folding, format, hierarchy, + hover, includes, inlay, inline, large, lens, linked, nav, on_type, pairs, ports, rename, + selection, settings, signature, symbols, sync, tokens, type_def, type_hierarchy, watch, }; /// What the client said it can do, read once at `initialize` because that is @@ -112,6 +112,9 @@ pub struct ClientAbilities { /// which error code declines `semanticTokens/full` on a large buffer — /// see `docs/features/large-file-mode/README.md`. pub token_server_cancel: bool, + /// Whether the client hosts the custom lucisv hierarchy sidebar and wants + /// a notification whenever the installed workspace index changes. + pub hierarchy_view: bool, } /// Everything the server owns. @@ -142,6 +145,8 @@ pub struct Server { /// buffer's text, and the workspace index. It is the whole of a /// diagnostic `resultId`; see `docs/features/pull-diagnostics/README.md`. generation: u64, + /// Revision of the completed index exposed to the custom hierarchy view. + hierarchy_revision: u64, /// The last full-or-delta semantic-token answer for each open buffer — /// what a delta is computed *against*. Dropped on `didClose`, so this /// only ever holds what the editor is showing. See @@ -310,6 +315,7 @@ impl Server { request_ids: 0, pending: HashMap::new(), generation: 0, + hierarchy_revision: 0, tokens: HashMap::new(), token_results: 0, indexings: 0, @@ -347,6 +353,7 @@ impl Server { if server.stopped { return server; } + server.hierarchy_index_changed(); // A buffer can now be *opened* during the startup scan, and what was // published for it then was computed against a half-built index. This // is the same debt a rescan pays at the end of `reindex`, owed here @@ -527,6 +534,26 @@ impl Server { self.answering_a_rescan || self.rescan_wanted || !self.held.is_empty() } + /// Whether the installed index covers the whole scope with no indexing + /// work outstanding — what the hierarchy snapshot reports as `complete`. + /// + /// **Both clauses, not just `scanning`.** `!self.scanning` alone would be + /// answering "is a scan running *this instant*", and a snapshot taken + /// between a finished scan and a rescan already asked for would call a + /// stale index complete. Today [`Server::must_wait`] makes that + /// unreachable — a request arriving with `rescan_wanted` set or anything + /// `held` is set aside rather than answered, so a snapshot only ever + /// reaches this function when both are already clear, and `rescan_wanted` + /// is in any case only ever set while `scanning` is true. Saying it here + /// anyway costs nothing and means the honesty of the flag does not depend + /// on a scheduling invariant two hundred lines away staying true; a + /// hypothetical future exemption from `must_wait` would degrade the flag, + /// not break it. Pinned by + /// `a_snapshot_is_never_answered_complete_while_a_rescan_is_owed`. + fn index_is_complete(&self) -> bool { + !self.scanning && !self.must_wait() + } + // ------------------------------------------------------------------ // requests // ------------------------------------------------------------------ @@ -752,6 +779,11 @@ impl Server { None => Ok(Value::Null), } }), + design_hierarchy::METHOD => to_value(design_hierarchy::snapshot( + &self.workspace, + self.hierarchy_revision, + self.index_is_complete(), + )), // A rename the engine declines comes back as a request error // carrying its own sentence, which is what an editor shows in the // rename box. `prepareRename` declines the same way, so the box @@ -1808,6 +1840,7 @@ impl Server { return false; } self.refresh_code_lenses(); + self.hierarchy_index_changed(); self.generation += 1; for uri in self.workspace.open_uris() { self.publish(&uri); @@ -1875,6 +1908,7 @@ impl Server { ) }); self.refresh_code_lenses(); + self.hierarchy_index_changed(); self.generation += 1; self.report_scope(warnings); for uri in self.workspace.open_uris() { @@ -1903,6 +1937,7 @@ impl Server { // the bar names the scan, and everything after it is work done on the // scan's result. self.refresh_code_lenses(); + self.hierarchy_index_changed(); // Every open buffer's diagnostics are computed against the index, so a // pulling client's cached answers are all stale from here. self.generation += 1; @@ -2124,6 +2159,19 @@ impl Server { self.send_request(CodeLensRefresh::METHOD, ()); } + /// Publish a new completed hierarchy revision after any index mutation. + fn hierarchy_index_changed(&mut self) { + self.hierarchy_revision = self.hierarchy_revision.saturating_add(1); + if !self.abilities.hierarchy_view { + return; + } + notify_on( + &self.connection, + design_hierarchy::CHANGED_METHOD, + serde_json::json!({ "revision": self.hierarchy_revision }), + ); + } + /// One `$/progress` notification for a token the client already knows. fn progress(&self, token: ProgressToken, value: WorkDoneProgress) { progress_on(&self.connection, &token, value); @@ -5412,6 +5460,103 @@ mod tests { assert!(session.requests().is_empty(), "silence, on every rescan path"); } + #[test] + fn the_hierarchy_view_gets_a_snapshot_and_one_notification_per_completed_index() { + let tree = Tree::new("hierarchyviewrefresh"); + tree.write("sub.sv", "module sub; endmodule\n"); + tree.write("top.sv", "module top; sub u (); endmodule\n"); + let abilities = ClientAbilities { hierarchy_view: true, ..Default::default() }; + let mut session = Session::wide_with(vec![tree.path.clone()], abilities); + + let started: Vec = session + .drain() + .into_iter() + .filter_map(|message| match message { + Message::Notification(notification) + if notification.method == design_hierarchy::CHANGED_METHOD => + { + Some(notification.params) + } + _ => None, + }) + .collect(); + assert_eq!(started, [serde_json::json!({ "revision": 1 })]); + + let snapshot = session.result(design_hierarchy::METHOD, serde_json::json!({})); + assert_eq!(snapshot["revision"], 1); + assert_eq!(snapshot["complete"], true); + assert_eq!(snapshot["modules"].as_array().expect("modules").len(), 2); + + tree.write("top.sv", "module top; sub renamed (); endmodule\n"); + session.watched(&[tree.path.join("top.sv")]); + let changed: Vec = session + .drain() + .into_iter() + .filter_map(|message| match message { + Message::Notification(notification) + if notification.method == design_hierarchy::CHANGED_METHOD => + { + Some(notification.params) + } + _ => None, + }) + .collect(); + assert_eq!(changed, [serde_json::json!({ "revision": 2 })]); + let snapshot = session.result(design_hierarchy::METHOD, serde_json::json!({})); + assert_eq!(snapshot["revision"], 2); + let top = snapshot["modules"] + .as_array() + .expect("modules") + .iter() + .find(|module| module["moduleName"] == "top") + .expect("top"); + assert_eq!(top["instances"][0]["instanceName"], "renamed"); + } + + /// `complete` says "this is the whole workspace", and the window it has to + /// be honest about is the one between a finished scan and a rescan already + /// asked for — where `scanning` alone is false over an index that is about + /// to be rebuilt. Two answers, both pinned here: the flag itself is false, + /// and the request does not reach it at all, because `must_wait` sets a + /// request owed a rescan aside instead of answering it. + #[test] + fn a_snapshot_is_never_answered_complete_while_a_rescan_is_owed() { + let tree = Tree::new("hierarchycomplete"); + tree.write("top.sv", "module top; endmodule\n"); + let abilities = ClientAbilities { hierarchy_view: true, ..Default::default() }; + let mut session = Session::wide_with(vec![tree.path.clone()], abilities); + session.drain(); + assert!(session.server.index_is_complete(), "settled: nothing is owed"); + assert_eq!( + session.result(design_hierarchy::METHOD, serde_json::json!({}))["complete"], + true + ); + + session.server.rescan_wanted = true; + assert!(!session.server.scanning, "premise: no scan is running this instant"); + assert!(!session.server.index_is_complete(), "but one is owed, so nothing is complete"); + + let request = Message::Request(Request::new( + RequestId::from(99), + design_hierarchy::METHOD.to_string(), + serde_json::json!({}), + )); + assert!(!session.batch(vec![request])); + assert_eq!(session.server.held.len(), 1, "the snapshot waits for the rescan"); + assert!(session.answers().is_empty(), "nothing was answered off the stale index"); + } + + #[test] + fn a_client_without_the_hierarchy_view_gets_no_custom_notifications() { + let tree = Tree::new("nohierarchyviewrefresh"); + tree.write("top.sv", "module top; endmodule\n"); + let session = Session::wide(vec![tree.path.clone()], false); + assert!(session.drain().into_iter().all(|message| { + !matches!(message, Message::Notification(notification) + if notification.method == design_hierarchy::CHANGED_METHOD) + })); + } + #[test] fn the_refresh_rides_after_the_indexing_bar_comes_down() { // The documented order: the bar names the scan, and the refresh is diff --git a/crates/lucisv_server/src/state.rs b/crates/lucisv_server/src/state.rs index a2af725..94c37e7 100644 --- a/crates/lucisv_server/src/state.rs +++ b/crates/lucisv_server/src/state.rs @@ -183,7 +183,14 @@ 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, &self.line_index) + FileFacts::from_analysis( + path, + &self.tree, + &self.defines, + &self.semantics, + &self.text, + &self.line_index, + ) } /// The completion words this buffer contributes, read off the tokens it was diff --git a/crates/vlog_parser/src/line_index.rs b/crates/vlog_parser/src/line_index.rs index 35eef39..39a7458 100644 --- a/crates/vlog_parser/src/line_index.rs +++ b/crates/vlog_parser/src/line_index.rs @@ -46,6 +46,30 @@ impl LineIndex { (line as u32, offset - self.line_starts[line - 1] + 1) } + /// The **0-based** line and **UTF-16** column of a byte offset — the units + /// a language-server `Position` counts in, as opposed to + /// [`line_col`](Self::line_col)'s 1-based bytes. `text` must be the text + /// this index was built from. + /// + /// An offset inside a multi-byte character is floored to that character's + /// start, and the `\r` of a CRLF line ending is not part of its line's + /// content. It lives here, beside the table it reads, because two callers + /// need the same answer: a server converting a span for the wire, and the + /// semantic index recording a declaration's position so no one has to. + pub fn utf16_position(&self, text: &str, offset: u32) -> (u32, u32) { + let mut floored = (offset as usize).min(text.len()); + while floored > 0 && !text.is_char_boundary(floored) { + floored -= 1; + } + let (line, _) = self.line_col(floored as u32); + let start = self.line_range(line).map_or(0, |r| r.start) as usize; + let slice = text.get(start..floored).unwrap_or(""); + // LSP line content excludes the whole `\r\n`; this index keeps the + // `\r` as an ordinary byte of its line, so drop it here. + let slice = slice.strip_suffix('\r').unwrap_or(slice); + (line - 1, utf16_len(slice)) + } + /// The byte offset of a 1-based line and column, or `None` if the text /// has no such line. A column past the end of its line is clamped to the /// line's end, so the result never lands on another line. @@ -77,6 +101,17 @@ impl LineIndex { } } +/// How many UTF-16 code units a string occupies — the unit LSP counts in. +/// +/// ASCII is answered by the length, which is what source text almost always +/// is; the decoding loop is for the rest. +fn utf16_len(s: &str) -> u32 { + if s.is_ascii() { + return s.len() as u32; + } + s.chars().map(|c| c.len_utf16() as u32).sum() +} + #[cfg(test)] mod tests { use super::*; @@ -141,6 +176,33 @@ mod tests { } } + #[test] + fn utf16_positions_are_zero_based_and_count_code_units() { + let src = "module m;\n// 🎉 é\nendmodule"; + let idx = LineIndex::new(src); + assert_eq!(idx.utf16_position(src, 0), (0, 0)); + assert_eq!(idx.utf16_position(src, 7), (0, 7)); + assert_eq!(idx.utf16_position(src, 10), (1, 0)); + let party = src.find('🎉').unwrap() as u32; + assert_eq!(idx.utf16_position(src, party), (1, 3)); + // Four UTF-8 bytes, two UTF-16 units — the surrogate pair. + assert_eq!(idx.utf16_position(src, party + 4), (1, 5)); + // An offset inside the pair floors to its start. + for inside in 1..4 { + assert_eq!(idx.utf16_position(src, party + inside), (1, 3)); + } + assert_eq!(idx.utf16_position(src, src.len() as u32 + 99), (2, 9)); + } + + #[test] + fn a_crlf_is_not_part_of_its_lines_utf16_content() { + let src = "ab\r\ncd\r\n"; + let idx = LineIndex::new(src); + assert_eq!(idx.utf16_position(src, 2), (0, 2), "at the `\\r`"); + assert_eq!(idx.utf16_position(src, 3), (0, 2), "at the `\\n`, past the `\\r`"); + assert_eq!(idx.utf16_position(src, 4), (1, 0)); + } + #[test] fn out_of_range_positions_are_clamped() { let src = "abc\nde"; diff --git a/crates/vlog_semantic/src/facts.rs b/crates/vlog_semantic/src/facts.rs index 4d0e0e6..defb2a4 100644 --- a/crates/vlog_semantic/src/facts.rs +++ b/crates/vlog_semantic/src/facts.rs @@ -20,13 +20,16 @@ use vlog_parser::defines::{Define, DefineKind, DefineTable}; use vlog_parser::span::TextRange; use crate::model::SymbolKind; -use crate::workspace::{Decl, DeclLines, DeclSite, FileFacts, ReferenceFact, SiteFact}; +use crate::workspace::{ + Decl, DeclLines, DeclPositions, DeclSite, FileFacts, InstanceOccurrence, ReferenceFact, + SiteFact, Utf16Pos, Utf16Range, +}; /// 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 = 4; +pub const FACTS_FORMAT: u32 = 5; impl FileFacts { /// These facts as one line's worth of fields, tab-separated. @@ -47,6 +50,10 @@ impl FileFacts { out.tag("U", self.units.len()); for decl in &self.units { out.decl(decl); + // Only the `U` group carries client positions, so the `M` group + // below stays exactly as wide as it was — see + // `vlog_semantic::DeclPositions` for why members are left out. + out.positions(&decl.lines.positions.unwrap_or_default()); } out.tag("M", self.members.len()); for (unit, decl) in &self.members { @@ -58,6 +65,14 @@ impl FileFacts { out.text(module); out.site(&site.owner); out.range(site.site_span); + out.num(site.instances.len() as u32); + for instance in &site.instances { + out.text(&instance.name); + out.range(instance.name_span); + out.range(instance.span); + out.utf16(instance.name_positions); + out.utf16(instance.positions); + } } out.tag("S", self.subclasses.len()); for (base, subclass) in &self.subclasses { @@ -89,7 +104,9 @@ impl FileFacts { } let mut units = Vec::new(); for _ in 0..input.tag("U")? { - units.push(input.decl()?); + let mut decl = input.decl()?; + decl.lines.positions = Some(input.positions()?); + units.push(decl); } let mut members = Vec::new(); for _ in 0..input.tag("M")? { @@ -99,7 +116,18 @@ impl FileFacts { for _ in 0..input.tag("I")? { let module = input.text()?; let owner = input.site()?; - instantiations.push((module, SiteFact { owner, site_span: input.range()? })); + let site_span = input.range()?; + let mut instances = Vec::new(); + for _ in 0..input.num()? { + instances.push(InstanceOccurrence { + name: input.text()?, + name_span: input.range()?, + span: input.range()?, + name_positions: input.utf16()?, + positions: input.utf16()?, + }); + } + instantiations.push((module, SiteFact { owner, site_span, instances })); } let mut subclasses = Vec::new(); for _ in 0..input.tag("S")? { @@ -185,6 +213,7 @@ impl Writer { self.field(); self.out.push_str(kind_name(decl.kind)); self.range(decl.name_span); + self.range(decl.decl_span); // The detail span is written unconditionally — `0 0` for the `None` // every ordinary declaration has — so the stream stays flat. Adding it // changed what a record holds, so `FACTS_FORMAT` is bumped and a store @@ -206,6 +235,20 @@ impl Writer { self.num(decl.lines.detail.unwrap_or(0)); } + /// One [`Utf16Range`]: four numbers, in the order a reader takes them. + fn utf16(&mut self, range: Utf16Range) { + self.num(range.start.line); + self.num(range.start.character); + self.num(range.end.line); + self.num(range.end.character); + } + + /// A file-scope declaration's two client ranges, written after its decl. + fn positions(&mut self, positions: &DeclPositions) { + self.utf16(positions.name); + self.utf16(positions.decl); + } + fn site(&mut self, site: &DeclSite) { self.text(&site.name); self.range(site.name_span); @@ -318,6 +361,7 @@ impl<'a> Reader<'a> { let name = self.text()?; let kind = kind_of(self.next()?)?; let name_span = self.range()?; + let decl_span = self.range()?; // The mirror of the encoder's unconditional pair: `(0, 0)` is the // `None`, and a real span can never be, because a declaration's span // is never empty. @@ -329,9 +373,26 @@ impl<'a> Reader<'a> { // 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 }) + // Client positions are not one of a declaration's shared fields: a + // caller reading the `U` group takes them from `positions()` next, and + // a member has none at all (`vlog_semantic::DeclPositions`). + let lines = DeclLines { + name: name_line, + detail: (detail_line != 0).then_some(detail_line), + positions: None, + }; + Some(Decl { name, name_span, decl_span, kind, detail_span, lines }) + } + + fn utf16(&mut self) -> Option { + Some(Utf16Range { + start: Utf16Pos { line: self.num()?, character: self.num()? }, + end: Utf16Pos { line: self.num()?, character: self.num()? }, + }) + } + + fn positions(&mut self) -> Option { + Some(DeclPositions { name: self.utf16()?, decl: self.utf16()? }) } fn site(&mut self) -> Option { diff --git a/crates/vlog_semantic/src/lib.rs b/crates/vlog_semantic/src/lib.rs index 5cc8beb..f2c1a24 100644 --- a/crates/vlog_semantic/src/lib.rs +++ b/crates/vlog_semantic/src/lib.rs @@ -31,9 +31,10 @@ pub use model::{ SymbolId, SymbolKind, }; pub use workspace::{ - index_order, resolve_external, DeclLines, DeclSite, Def, Definition, DefinitionKey, - ExternalResolutions, ExternalTarget, FileFacts, FileId, IndexBuilder, IndexCounts, - InheritanceEdge, InstantiationEdge, ReferenceSite, WorkspaceIndex, WorkspaceSymbol, + index_order, resolve_external, DeclLines, DeclPositions, DeclSite, Def, Definition, + DefinitionKey, ExternalResolutions, ExternalTarget, FileFacts, FileId, IndexBuilder, + IndexCounts, InheritanceEdge, InstanceOccurrence, InstantiationEdge, ReferenceSite, Utf16Pos, + Utf16Range, WorkspaceIndex, WorkspaceSymbol, }; use std::collections::HashMap; diff --git a/crates/vlog_semantic/src/workspace.rs b/crates/vlog_semantic/src/workspace.rs index de4d916..9b7da0b 100644 --- a/crates/vlog_semantic/src/workspace.rs +++ b/crates/vlog_semantic/src/workspace.rs @@ -35,6 +35,8 @@ pub struct Def { pub file: FileId, /// Byte range of the declared name inside that file. pub name_span: TextRange, + /// Byte range of the complete construct that declares the name. + pub decl_span: TextRange, /// What kind of declaration it is, for an icon and for hover text. pub kind: SymbolKind, /// Where the declaration is *completed* when not at `name_span` — a @@ -60,6 +62,7 @@ pub struct Def { /// 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. +/// [`DeclPositions`] is the first of those added fields. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub struct DeclLines { /// 1-based line the declared name is on. @@ -67,6 +70,9 @@ pub struct DeclLines { /// 1-based line the `detail_span` starts on, `None` exactly when there is /// no detail span. pub detail: Option, + /// The same two spans as a *client* counts positions — `Some` for a + /// file-scope declaration, `None` for a member. See [`DeclPositions`]. + pub positions: Option, } impl DeclLines { @@ -77,10 +83,62 @@ impl DeclLines { DeclLines { name: lines.line_col(name_span.start).0, detail: detail_span.map(|span| lines.line_col(span.start).0), + positions: None, } } } +/// One position as a language-server client counts one: a **0-based** line and +/// **UTF-16 code units** into it — not [`LineIndex`]'s 1-based bytes. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PartialOrd, Ord)] +pub struct Utf16Pos { + /// 0-based line. + pub line: u32, + /// UTF-16 code units from the start of that line's content. + pub character: u32, +} + +/// A byte [`TextRange`] as a client sees it, both ends converted once when the +/// file was scanned. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PartialOrd, Ord)] +pub struct Utf16Range { + pub start: Utf16Pos, + pub end: Utf16Pos, +} + +impl Utf16Range { + /// A span's two ends, converted through the file's own line index. + pub(crate) fn of(src: &str, lines: &LineIndex, span: TextRange) -> Utf16Range { + Utf16Range { start: pos(src, lines, span.start), end: pos(src, lines, span.end) } + } +} + +fn pos(src: &str, lines: &LineIndex, offset: u32) -> Utf16Pos { + let (line, character) = lines.utf16_position(src, offset); + Utf16Pos { line, character } +} + +/// Where a **file-scope** declaration sits in its file, in the units a client +/// speaks — so pointing an editor at a module declared in a file nobody has +/// open costs no read of that file at all. +/// +/// **Why only file-scope declarations carry this.** A member — a port, a +/// parameter, a class field — is a [`Decl`] exactly as a unit is, and there are +/// two orders of magnitude more of them: on opentitan, 1 544 modules against +/// hundreds of thousands of members, so giving every declaration eight more +/// numbers would have roughly doubled the persistent store to serve a caller +/// that does not exist. The units and the members are written in two separate +/// groups of a record, so "units carry positions, members do not" costs a +/// member no field at all — and the day a member wants them, it is the same +/// eight fields in the other group plus the [`crate::FACTS_FORMAT`] bump. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct DeclPositions { + /// The declared name's own range — an editor's selection range. + pub name: Utf16Range, + /// The whole declaring construct's range. + pub decl: Utf16Range, +} + /// Stable identity of one indexed declaration inside the current index. /// /// A [`FileId`] may move when a file is added or removed, so this key survives @@ -154,6 +212,30 @@ pub struct InstantiationEdge { pub owner: DeclSite, /// Byte range of the instantiated module's name at the site. pub site_span: TextRange, + /// The individual instances the statement declares, in source order. + /// + /// The edge itself deliberately remains one-per-statement: call hierarchy + /// and code lenses have always treated `sub u1 (), u2 ();` as one written + /// call site. Instance-oriented clients can flatten this list without + /// changing that census. + pub instances: Vec, +} + +/// One named instance inside an [`InstantiationEdge`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct InstanceOccurrence { + /// Instance name as written (`u_fifo`). + pub name: String, + /// Byte range of the instance name. + pub name_span: TextRange, + /// Byte range of the whole instance, including dimensions and connections. + pub span: TextRange, + /// `name_span` as a client counts positions, converted when the file was + /// scanned — the same reason [`DeclPositions`] exists, for the other half + /// of what a design-hierarchy row points at. + pub name_positions: Utf16Range, + /// `span` likewise. + pub positions: Utf16Range, } /// One class that extends another. @@ -397,6 +479,22 @@ impl WorkspaceIndex { out } + /// Every file-scope declaration of one kind, under its name, in name + /// order. + /// + /// The cheap half of [`WorkspaceIndex::workspace_symbols`] for a caller + /// that wants units and never members: it walks the unit table alone and + /// sorts nothing, where `workspace_symbols("")` walks every member of every + /// unit and sorts the lot. On opentitan that is 1 544 modules out of + /// hundreds of thousands of declarations, and the difference is 15 ms per + /// call (`docs/features/vscode-hierarchy-sidebar/README.md`). + pub fn units_of(&self, kind: SymbolKind) -> impl Iterator { + self.units + .iter() + .flat_map(|(name, defs)| defs.iter().map(move |def| (name.as_str(), def))) + .filter(move |(_, def)| def.kind == kind) + } + /// How many unit names and member names are indexed. pub fn counts(&self) -> IndexCounts { IndexCounts { @@ -556,15 +654,18 @@ impl WorkspaceIndex { } for symbol in self.workspace_symbols("") { out.push_str(&format!( - "sym {} in {:?} {:?} {}:{}..{} line={} detail={:?}\n", + "sym {} in {:?} {:?} {}:{}..{} decl={}..{} line={} detail={:?} at={:?}\n", symbol.name, symbol.container, symbol.def.kind, symbol.def.file.0, symbol.def.name_span.start, symbol.def.name_span.end, + symbol.def.decl_span.start, + symbol.def.decl_span.end, symbol.def.lines.name, - symbol.def.lines.detail + symbol.def.lines.detail, + symbol.def.lines.positions )); } for (definition, sites) in &self.reference_sites { @@ -599,6 +700,18 @@ impl WorkspaceIndex { edge.site_span.start, edge.site_span.end )); + for instance in &edge.instances { + out.push_str(&format!( + " instance {} name {}..{} span {}..{} at {:?} {:?}\n", + instance.name, + instance.name_span.start, + instance.name_span.end, + instance.span.start, + instance.span.end, + instance.name_positions, + instance.positions + )); + } } } for (name, edges) in self.subclasses() { @@ -676,6 +789,7 @@ impl WorkspaceIndex { file, owner: edge.owner.clone(), site_span: edge.site_span, + instances: edge.instances.clone(), }); } for (base, subclass) in &facts.subclasses { @@ -776,26 +890,42 @@ impl Affected { pub(crate) struct Decl { pub(crate) name: String, pub(crate) name_span: TextRange, + pub(crate) decl_span: TextRange, pub(crate) kind: SymbolKind, pub(crate) detail_span: Option, pub(crate) lines: DeclLines, } impl Decl { - fn of(symbol: &Symbol, lines: &LineIndex) -> Decl { + /// A member's declaration: lines only, no client positions — see + /// [`DeclPositions`] for why the cheap half is the only half a member gets. + fn member(symbol: &Symbol, lines: &LineIndex) -> Decl { Decl { name: symbol.name.clone(), name_span: symbol.name_span, + decl_span: symbol.decl_span, kind: symbol.kind, detail_span: symbol.detail_span, lines: DeclLines::of(lines, symbol.name_span, symbol.detail_span), } } + /// A file-scope declaration: the same, plus the two ranges a client is + /// pointed at, converted here so no one converts them later. + fn unit(symbol: &Symbol, src: &str, lines: &LineIndex) -> Decl { + let mut decl = Decl::member(symbol, lines); + decl.lines.positions = Some(DeclPositions { + name: Utf16Range::of(src, lines, symbol.name_span), + decl: Utf16Range::of(src, lines, symbol.decl_span), + }); + decl + } + fn def(&self, file: FileId) -> Def { Def { file, name_span: self.name_span, + decl_span: self.decl_span, kind: self.kind, detail_span: self.detail_span, lines: self.lines, @@ -809,6 +939,7 @@ impl Decl { pub(crate) struct SiteFact { pub(crate) owner: DeclSite, pub(crate) site_span: TextRange, + pub(crate) instances: Vec, } /// Everything one file contributes to an index: read while the file is parsed, @@ -885,18 +1016,20 @@ impl FileFacts { /// 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`]). + /// `src` and `lines` are asked for rather than built here because a caller + /// with a finished analysis in hand — a server holding an open buffer — + /// already has both, and because a record now carries each declaration's + /// line ([`DeclLines`]) and each file-scope declaration's client position + /// ([`DeclPositions`]), neither of which can be read off a tree alone. pub fn from_analysis( path: PathBuf, tree: &SourceFile, defines: &DefineTable, sem: &Semantics, + src: &str, lines: &LineIndex, ) -> FileFacts { - facts_from_analysis(path, tree, defines.clone(), sem, lines) + facts_from_analysis(path, tree, defines.clone(), sem, src, lines) } /// The file these facts were read from. @@ -913,7 +1046,7 @@ fn facts_of(path: PathBuf, src: &str) -> FileFacts { // 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) + facts_from_analysis(path, &tree, defines, &sem, src, &lines) } /// Read off what one file contributes, from its finished analysis. @@ -922,6 +1055,7 @@ fn facts_from_analysis( tree: &SourceFile, defines: DefineTable, sem: &Semantics, + src: &str, lines: &LineIndex, ) -> FileFacts { let mut facts = FileFacts { @@ -929,7 +1063,7 @@ fn facts_from_analysis( defines, units: Vec::new(), members: Vec::new(), - instantiations: edges_of(tree), + instantiations: edges_of(tree, src, lines), subclasses: inheritance_of(tree), references: Vec::new(), }; @@ -943,7 +1077,7 @@ fn facts_from_analysis( if !is_unit(unit.kind) || unit.name_span.is_empty() { continue; } - facts.units.push(Decl::of(unit, lines)); + facts.units.push(Decl::unit(unit, src, lines)); collect_members(sem, unit, lines, &mut facts.members); } let exported: HashSet<(u32, u32)> = facts @@ -986,7 +1120,7 @@ fn facts_from_analysis( /// hierarchy reads a buffer with — so the workspace-wide census and the /// per-file one cannot disagree. A site written at file scope has no /// instantiating module and is not an edge. -fn edges_of(tree: &SourceFile) -> Vec<(String, SiteFact)> { +fn edges_of(tree: &SourceFile, src: &str, lines: &LineIndex) -> Vec<(String, SiteFact)> { instantiations::sites(&tree.items) .into_iter() .filter_map(|site| { @@ -1000,6 +1134,18 @@ fn edges_of(tree: &SourceFile) -> Vec<(String, SiteFact)> { span: owner.span, }, site_span: site.inst.module_span, + instances: site + .inst + .instances + .iter() + .map(|instance| InstanceOccurrence { + name: instance.name.clone(), + name_span: instance.name_span, + span: instance.span, + name_positions: Utf16Range::of(src, lines, instance.name_span), + positions: Utf16Range::of(src, lines, instance.span), + }) + .collect(), }, )) }) @@ -1041,7 +1187,7 @@ fn collect_members( if !is_exported(unit.kind, member.kind) || member.name_span.is_empty() { continue; } - out.push((unit.name.clone(), Decl::of(member, lines))); + out.push((unit.name.clone(), Decl::member(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, diff --git a/crates/vlog_semantic/tests/workspace.rs b/crates/vlog_semantic/tests/workspace.rs index c2d4c9f..3e5d227 100644 --- a/crates/vlog_semantic/tests/workspace.rs +++ b/crates/vlog_semantic/tests/workspace.rs @@ -6,7 +6,7 @@ use vlog_parser::defines::{collect_defines, DefineTable}; use vlog_parser::{parse_source_tolerant, parse_tolerant, tokenize}; use vlog_semantic::{ analyze, resolve_external, Def, Definition, ExternalTarget, FileFacts, FileId, Resolution, - Semantics, SymbolKind, WorkspaceIndex, + Semantics, SymbolKind, Utf16Pos, WorkspaceIndex, }; /// Build an index from `(path, source)` literals, as a server would from disk. @@ -1414,6 +1414,16 @@ endmodule let text = files[0].1; assert_eq!(&text[sites[0].site_span.as_range()], "sub"); assert_eq!(&text[sites[0].owner.name_span.as_range()], "top"); + assert_eq!( + sites[0].instances.iter().map(|instance| instance.name.as_str()).collect::>(), + ["u1", "u2"], + "the statement edge keeps each instance without becoming two call sites" + ); + for instance in &sites[0].instances { + assert_eq!(&text[instance.name_span.as_range()], instance.name); + assert!(instance.span.start <= instance.name_span.start); + assert!(instance.name_span.end <= instance.span.end); + } assert!(sites[0].owner.span.start <= sites[0].owner.name_span.start); assert!(sites[0].owner.name_span.end <= sites[0].owner.span.end); } @@ -1699,6 +1709,36 @@ fn a_records_every_field_survives_the_round_trip() { // inheritance edges — so this is the whole record, not a summary of it. assert_eq!(back, facts); assert_eq!(back.encode(), Some(line), "and re-encodes byte for byte"); + let mut builder = vlog_semantic::IndexBuilder::new(); + builder.add_facts(back); + let restored = builder.finish(); + let instances = &restored.instantiations_of("sub")[0].instances; + assert_eq!(instances.len(), 1); + assert_eq!(instances[0].name, "u_sub"); + assert_eq!(&EVERY_FIELD[instances[0].name_span.as_range()], "u_sub"); + assert_eq!(&EVERY_FIELD[instances[0].span.as_range()], "u_sub ()"); +} + +/// What format 4 wrote for an instantiation: the statement ended immediately +/// after its module-name span, before the per-instance count and records added +/// in format 5. It must be dropped, not field-shifted into the following `S` +/// tag. +#[test] +fn a_format_4_record_without_instance_occurrences_is_rejected() { + let facts = + FileFacts::of(PathBuf::from("/w/i.sv"), "module top; sub u1 (), u2 (); endmodule\n"); + let encoded = facts.encode().expect("encodes"); + let mut fields: Vec<&str> = encoded.split('\t').collect(); + let instances_at = fields.iter().position(|field| *field == "I").expect("I tag"); + assert_eq!(fields[instances_at + 1], "1", "one statement edge"); + // I,count,module, owner(name + two ranges), site range = ten fields. The + // next field is the occurrence count added in format 5; each occurrence is + // thirteen more — name, two byte ranges, two client ranges. + let occurrence_count_at = instances_at + 10; + assert_eq!(fields[occurrence_count_at], "2", "two individual instances"); + fields.drain(occurrence_count_at..occurrence_count_at + 1 + 2 * 13); + let format_4 = fields.join("\t"); + assert!(FileFacts::decode(&format_4).is_none(), "format 4 decoded as format 5"); } /// Every indexed declaration carries the line it is written on, so a caller @@ -1740,6 +1780,64 @@ fn crlf_and_multibyte_text_do_not_shift_a_declarations_line() { assert_eq!(index(&[("/w/w.sv", wide)]).units("m").first().expect("m").lines.name, 3); } +/// The extension `DeclLines` was shaped for, taken: a file-scope declaration +/// now also carries the two ranges a *client* is pointed at, in the units a +/// client counts in — 0-based lines and UTF-16 code units. +#[test] +fn a_file_scope_declaration_carries_its_client_ranges() { + let src = "// \u{1F389}\nmodule top;\nendmodule\n"; + let index = index(&[("/w/t.sv", src)]); + let positions = index.units("top").first().expect("top").lines.positions.expect("positions"); + assert_eq!(positions.name.start, Utf16Pos { line: 1, character: 7 }); + assert_eq!(positions.name.end, Utf16Pos { line: 1, character: 10 }); + assert_eq!(positions.decl.start, Utf16Pos { line: 1, character: 0 }); + assert_eq!(positions.decl.end, Utf16Pos { line: 2, character: 9 }); +} + +/// A multi-byte character before a name shifts its UTF-16 column away from the +/// byte column the spans are in — the whole reason the conversion is done here +/// rather than guessed at later. +#[test] +fn client_ranges_count_utf16_units_not_bytes() { + // `🎉` is four bytes and two UTF-16 units; `é` is two bytes and one. + let src = "/*\u{1F389}\u{e9}*/ module top; endmodule\n"; + let index = index(&[("/w/t.sv", src)]); + let def = index.units("top").first().expect("top"); + let positions = def.lines.positions.expect("positions"); + assert_eq!(def.name_span.start, src.find("top").expect("top") as u32, "the byte span"); + // `/*`, two units of `🎉`, one of `é`, `*/`, a space, then `module `. + assert_eq!(positions.name.start, Utf16Pos { line: 0, character: 15 }, "the client column"); + assert_eq!(positions.decl.start, Utf16Pos { line: 0, character: 8 }); +} + +/// Every instance occurrence carries the same pair, for the other half of what +/// a design-hierarchy row points at. +#[test] +fn every_instance_occurrence_carries_its_client_ranges() { + let src = "module top;\n sub u1 (), u2 ();\nendmodule\n"; + let index = index(&[("/w/t.sv", src)]); + let edges = index.instantiations_of("sub"); + let instances = &edges[0].instances; + assert_eq!(instances.len(), 2); + assert_eq!(instances[0].name_positions.start, Utf16Pos { line: 1, character: 6 }); + assert_eq!(instances[0].name_positions.end, Utf16Pos { line: 1, character: 8 }); + assert_eq!(instances[0].positions.start, Utf16Pos { line: 1, character: 6 }); + assert_eq!(instances[1].name_positions.start, Utf16Pos { line: 1, character: 13 }); +} + +/// A member does not carry them, deliberately: there are two orders of +/// magnitude more members than units and no caller for theirs, so the record +/// spends nothing on them (`DeclPositions`). +#[test] +fn a_member_carries_lines_but_no_client_ranges() { + let src = "module m (\n input wire clk\n);\nendmodule\n"; + let index = index(&[("/w/m.sv", src)]); + let port = index.member("m", "clk").first().expect("the port"); + assert_eq!(port.lines.name, 2, "a member still carries its line"); + assert_eq!(port.lines.positions, None); + assert!(index.units("m").first().expect("m").lines.positions.is_some(), "the unit does"); +} + /// 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 @@ -1816,34 +1914,52 @@ fn a_format_3_record_with_two_declarations_is_rejected_not_misread() { ); } -/// 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. +/// The generalization of `index_cache`'s old-record stripper: turn a record +/// this format wrote back into what `FACTS_FORMAT` 3 wrote for the same file — +/// remove, from every one of `units` unit-decls and `members` member-decls, the +/// client positions added in format 5, the `decl_span` added in format 5, and +/// the two trailing (`name_line`, `detail_line`) fields added in format 4. +/// 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; + // A member's decl = name, kind, name_span×2, decl_span×2, detail_span×2, + // line×2 — 10 fields. A unit's is that plus its two client ranges, four + // numbers each — 18. + let members_at = units_at + 2 + units * UNIT_DECL_FIELDS; 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); + let member_decl_starts: Vec = + (0..members).map(|m| members_at + 2 + m * (MEMBER_DECL_FIELDS + 1) + 1).collect(); + let unit_decl_starts: Vec = + (0..units).map(|u| units_at + 2 + u * UNIT_DECL_FIELDS).collect(); + // Highest index first, so removing one strip does not move the others, and + // within one decl highest-first for the same reason. + let mut starts: Vec<(usize, bool)> = unit_decl_starts + .into_iter() + .map(|start| (start, true)) + .chain(member_decl_starts.into_iter().map(|start| (start, false))) + .collect(); + starts.sort_unstable_by_key(|start| std::cmp::Reverse(start.0)); + for (start, is_unit) in starts { + if is_unit { + fields.drain(start + MEMBER_DECL_FIELDS..start + UNIT_DECL_FIELDS); + } + fields.drain(start + 8..start + 10); + fields.drain(start + 4..start + 6); } fields.join("\t") } +/// Fields one member declaration occupies in a record this format writes. +const MEMBER_DECL_FIELDS: usize = 10; +/// The same for a unit, which also carries its two client ranges. +const UNIT_DECL_FIELDS: usize = MEMBER_DECL_FIELDS + 8; + #[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 @@ -2014,7 +2130,7 @@ fn facts_from_a_finished_analysis_are_byte_identical_to_facts_from_the_text() { let path = PathBuf::from("/w/x.sv"); 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, &lines); + let from_analysis = FileFacts::from_analysis(path, &tree, &defines, &sem, src, &lines); assert_eq!(from_analysis, from_text, "the records differ for {src:?}"); assert_eq!( from_analysis.encode(), @@ -2044,7 +2160,8 @@ fn the_two_ways_to_read_a_files_facts_agree_over_the_whole_corpus() { }; 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, &lines); + let from_analysis = + FileFacts::from_analysis(path.clone(), &tree, &defines, &sem, &src, &lines); assert_eq!( from_analysis.encode(), from_text.encode(), @@ -2097,6 +2214,7 @@ fn an_index_built_from_finished_analyses_fingerprints_the_same_as_one_built_from &tree, &defines, &sem, + src, &lines, )); } @@ -2113,6 +2231,7 @@ fn an_index_built_from_finished_analyses_fingerprints_the_same_as_one_built_from &tree, &defines, &sem, + changed, &lines, )); let mut parsed = from_text.clone(); diff --git a/docs/features/hover-line-index/README.md b/docs/features/hover-line-index/README.md index 893382a..220acf4 100644 --- a/docs/features/hover-line-index/README.md +++ b/docs/features/hover-line-index/README.md @@ -96,7 +96,15 @@ promised: - **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 + fields a `DeclLines` has. **Taken, 2026-08-29**, and it went exactly that + way: `docs/features/vscode-hierarchy-sidebar/README.md` added + `positions: Option` — the declared name's and the whole + declaration's ranges in the units a client counts in — for `FACTS_FORMAT` + 4 → 5, so a design-hierarchy snapshot needs no file text at all. The one + amendment that round made to the story above: those positions ride + **file-scope declarations only**, because members outnumber units by two + orders of magnitude and the record's `U` and `M` groups are separate, so + the absence costs a member nothing. A member still carries its lines. 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 diff --git a/docs/features/index-persistence/README.md b/docs/features/index-persistence/README.md index e1f9f0e..814af4d 100644 --- a/docs/features/index-persistence/README.md +++ b/docs/features/index-persistence/README.md @@ -221,13 +221,28 @@ impl WorkspaceIndex { `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 + declaration without reading that file. **4 → 5** (2026-08-29, + `docs/features/vscode-hierarchy-sidebar/README.md`): one bump for three + additions — each declaration's `decl_span`; a per-instance + `InstanceOccurrence` list on every instantiation edge (the edge itself is + still one per *statement*, so no census moved); and **client positions**, + 0-based lines and UTF-16 columns, on every file-scope declaration and every + instance occurrence, which is what lets the design-hierarchy snapshot answer + with no file read at all. Members deliberately get none: the `U` and `M` + groups of a record are separate, so "units carry positions, members do not" + costs a member no field, not even a presence flag — and members outnumber + units by two orders of magnitude. 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 + once. `a_store_from_any_previous_facts_format_is_dropped_not_misread` 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. + number it was pinned at, so each bump inherits the test; its + belt-and-braces half (a genuine previous-format record served past the + header) is re-derived at each bump — `as_a_format_4_record` at format 5. + The store grew 68 KB (2.9 %) for the lines at format 4, and a further + 212 KB (8.9 %) over the 860-file corpus for all of format 5 — of which the + client positions are 1.7 %, measured separately on the same corpus and again + on opentitan (1.9 % of a 24.7 MB store). - `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. @@ -363,9 +378,12 @@ 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 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, +carries its detail span (`0 0` when there is none, format 3), its two line +numbers (format 4), its `decl_span` and — for a file-scope declaration only — +its two client ranges of four numbers each (format 5); and an instantiation +edge carries a length-prefixed list of its individual instances, each a name, +two byte ranges and two client ranges. So a real record today is considerably +wider 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. diff --git a/docs/features/vscode-hierarchy-sidebar/README.md b/docs/features/vscode-hierarchy-sidebar/README.md new file mode 100644 index 0000000..dd68335 --- /dev/null +++ b/docs/features/vscode-hierarchy-sidebar/README.md @@ -0,0 +1,806 @@ +# vscode-hierarchy-sidebar + +## Goal + +Give the lucisv VS Code extension its own Activity Bar container with a +**Hierarchy** view: a persistent fuzzy-search field above an alphabetical, +folder-like module-instance tree. LSP call hierarchy deliberately groups a +module's calls by target module *type*; this view needs the other reading of the +same facts — every individual instance name, its source range, and every +declaration its type may name — so the server answers a custom +`lucisv/moduleHierarchy` snapshot and notifies `lucisv/moduleHierarchyChanged` +whenever the installed index changes. The snapshot is **flat**: the client picks +roots and opens paths, which keeps recursion out of the protocol and lets one +answer serve both rendering and search. This is a textual design hierarchy, not +an elaborator: generate loops appear once as written, both preprocessor arms may +appear, parameters are not evaluated, and instance arrays are not expanded into +numeric elements. + +For a design such as: + +```systemverilog +module TB; + top dut (); +endmodule + +module top; + block inst1 (); +endmodule + +module block; + leaf inst2 (); +endmodule +``` + +the view begins collapsed at `TB` and opens, one level at a time, to +`TB` → `dut (top)` → `inst1 (block)` → `inst2 (leaf)`. The root label is a +module name; every child label leads with the instance name and includes its +module type, so both names are visible and both are searchable. + +### Product behaviour (codex's specification, amended where noted) + +**Tree and roots.** + +- Show every uniquely declared module reachable from a root through instance + edges. Roots are modules with no resolved parent, sorted case-insensitively; + children are sorted by instance name, then module name, then source URI and + position for a deterministic tie-break. +- Show an unresolved instantiated type as a non-expandable warning row. + Navigation to the instance still works; "Show Definition" explains that no + definition is indexed. +- Keep an ambiguous type visible as a non-expandable warning row. "Show + Definition" offers a Quick Pick of candidates instead of guessing. +- After the ordinary zero-parent roots, add any declaration a root never + reaches because it sits in a recursive strongly connected component. Those + fallback roots are marked, and the repeated edge inside them is marked + `recursive` and does not open again, so `A -> B -> A` is visible without an + infinite tree. +- Two declarations of one module name in different files are distinct + definitions, identified by URI and position. +- The view reflects exactly the server's current index scope. +- **Amended, owner 2026-08-29: every level starts collapsed.** Nothing expands + on the view's behalf, on open or on refresh; the one exception is the ancestor + chain of a bookmarked row, which the user asked for by bookmarking. + +**Search.** + +- A real text input stays fixed above the tree — not a toolbar command, not an + InputBox. +- Matching is case-insensitive against exactly two fields, module name and + instance name. Never paths, filenames, directories, preview text, ports or + connection expressions. +- The scorer is a deterministic fuzzy subsequence with exact, prefix, + word-boundary and consecutive-character bonuses; an instance-name score wins a + tie against a module-name score by one. +- **Amended, owner 2026-08-29: a query renders a ranked, capped result list + rather than a filtered tree.** A flat model has no one path per instance, so a + match is one row that names the module writing it. The tree is not torn down + while searching, and clearing the query restores it — same rows open, no + snapshot re-request. Results cap at 200 with an `N more matches` line. + +**Navigation, context menu and bookmark.** + +- Clicking an instance selects its instance-name range at the instantiation; + clicking a root module selects its module declaration. +- The context menu is reachable with the mouse and with Shift+F10 / the Menu + key, and rows carry ARIA tree roles, levels, expanded state and labels: + - **Copy Full Path** — `TB.dut.inst1.inst2`; the root segment is the root + module name and every later segment an instance name. *Tree rows only.* + - **Show Definition** — opens the instantiated module's declaration and + selects its name; a Quick Pick when ambiguous, a concise warning when + unresolved. + - **Show Instance** — the normal instance click's destination. + - **Highlight / Bookmark** — one workspace-scoped bookmarked path, painted + with a yellow theme token, ancestors expanded and the row revealed. The + logical full path is persisted in `workspaceState`, re-resolved after every + refresh, and dropped with an explanation if it stops existing or stops being + unique. *Tree rows only.* + - **Open on the Right** — the module definition in `ViewColumn.Beside`, pinned + as a non-preview editor. +- **Removed, owner 2026-08-29: the five-line hover source preview.** See the + work log; it was the feature's last consumer of file text. + +### UI architecture + +One contributed `WebviewView`, not a `TreeDataProvider`: VS Code's native tree +API gives excellent rows and context menus but no persistent text input inside +the view, and a webview is the only stable API at the extension's VS Code floor +(`^1.82.0`) that satisfies the literal search-bar layout. `package.json` +contributes a `lucisv` Activity Bar container with a monochrome SVG icon, the +`lucisv.hierarchy` webview view, `onView:lucisv.hierarchy` activation, and +refresh / clear-bookmark commands. + +`extension.js` stays the lifecycle owner; the feature lives in focused CommonJS +modules: + +- `hierarchyModel.js` — response validation, the flat resident model, root + choice, lazy tree rows, cycle guards, full paths, sorting and the search + index. No `vscode` dependency, so plain Node tests cover it exhaustively. +- `hierarchyView.js` — the provider: server requests, the model, the expansion + set, navigation, clipboard, persistence and command dispatch. +- `media/hierarchy.js` / `hierarchy.css` — rendering, the search box, disclosure, + the accessible context menu and the message bridge. +- `images/hierarchy.svg` — the theme-neutral Activity Bar icon. + +The webview uses a nonce-based CSP, `localResourceRoots`, `asWebviewUri`, HTML +escaping and a fixed allow-list of message types. Rows carry opaque ids and the +extension resolves an id against its current model; no source text, filesystem +path or executable command ever comes back from DOM data. All colours are VS +Code theme variables, with a high-contrast border fallback for the bookmark row. + +### Explicit non-goals for the first delivery + +- Full SystemVerilog elaboration, parameter evaluation, preprocessor branch + selection, generate-loop expansion, or simulator-specific library binding. +- Searching ports, signals, files, source text, or full hierarchy paths. +- Multiple simultaneous bookmarks, bookmark sync across machines, drag-and-drop, + hierarchy editing, or changing the selected top from the view. +- Replacing the standard LSP call hierarchy; this sidebar is an + instance-oriented companion to it. + +## Assumptions + +- **A recorded position is a fact about the same snapshot the span is.** A + declaration's byte span and its client position (`vlog_semantic::DeclPositions`) + are read off one text in one pass, so a range and a span can never name + different generations of a file. Where a file changed on disk with nothing + telling the server, both are stale together — the same bargain + `docs/features/hover-line-index/README.md` struck for `DeclLines`. +- **A client position is 0-based lines and UTF-16 code units**, which is what an + LSP `Position` counts in and *not* what `LineIndex::line_col` reports. Both + the index and the wire converter go through one function, + `vlog_parser::LineIndex::utf16_position`, so they cannot answer differently. +- **Only file-scope declarations carry client positions.** A member is a `Decl` + exactly as a unit is, and there are two orders of magnitude more of them; see + Handshakes for the measurement that decided it. +- **A module type resolves to the modules of that name in the same snapshot.** + The server no longer repeats those declarations on every instance; the client + looks them up in its own module table, which is the identical set. +- **The tree is a reading of the index's scope.** If `lucisv.index.scope`, a + filelist, excludes or the large-file policy keeps a file out, it is out of the + hierarchy too. +- **A row id is stable while its declaration does not move.** Ids are composed + from a URI and the declaration's own start position, so the user's expansion + state survives a refresh, a rescan and a restart. + +## Handshakes + +### `vlog_semantic` — `FACTS_FORMAT` 4 → 5, and what it now carries + +One bump, three additions, all folded into the same number (this branch minted +5; nothing here mints a 6): + +```rust +pub struct Def { + pub file: FileId, + pub name_span: TextRange, + pub decl_span: TextRange, // new in 5 + pub kind: SymbolKind, + pub detail_span: Option, + pub lines: DeclLines, +} + +pub struct DeclLines { + pub name: u32, + pub detail: Option, + pub positions: Option, // new in 5 — Some for a unit +} + +/// 0-based line, UTF-16 code units — what a client counts in. +pub struct Utf16Pos { pub line: u32, pub character: u32 } +pub struct Utf16Range { pub start: Utf16Pos, pub end: Utf16Pos } +pub struct DeclPositions { pub name: Utf16Range, pub decl: Utf16Range } + +pub struct InstantiationEdge { + pub file: FileId, + pub owner: DeclSite, + pub site_span: TextRange, + pub instances: Vec, // new in 5 +} + +pub struct InstanceOccurrence { + pub name: String, + pub name_span: TextRange, + pub span: TextRange, + pub name_positions: Utf16Range, // new in 5 + pub positions: Utf16Range, // new in 5 +} + +// Two added parameters, because a record now carries client positions: +impl FileFacts { + pub fn from_analysis(path, tree, defines, sem, src: &str, lines: &LineIndex) -> FileFacts; +} +pub const FACTS_FORMAT: u32 = 5; // was 4 +``` + +`callHierarchy/incomingCalls`, outgoing calls and code-lens counts still read +the statement-level edge and its `site_span`, so `sub u1 (), u2 ();` remains +**one** call site there. The sidebar alone flattens `instances` into two rows. +There is no second instantiation census to drift from the first: `instances` is +populated from the same `instantiations::sites` walk the call hierarchy reads. + +**The carrier extends by gaining a field, exactly as `hover-line-index` +predicted.** `DeclLines` was documented as "a column, or a rendered preview, is +another field written beside these two"; `DeclPositions` is the first of those +fields, written in `Writer::decl`'s group and read in `Reader`'s, with the +format bump any record change owes. + +**Why only file-scope declarations carry positions.** Members — ports, +parameters, class fields — are `Decl`s exactly as units are, and on opentitan +there are 1 544 modules against hundreds of thousands of members. Giving every +declaration eight more numbers would have cost, by measurement of the record +shape, several megabytes on a 24.6 MB store to serve a caller that does not +exist. The units and the members are written in two separate groups of a record +(`U` and `M`), so "units carry positions, members do not" costs a member **no +field at all** — not even a presence flag. The day a member wants them, it is +the same eight fields in the other group plus a bump. + +### `vlog_semantic` — `WorkspaceIndex::units_of` + +```rust +pub fn units_of(&self, kind: SymbolKind) -> impl Iterator; +``` + +The cheap half of `workspace_symbols("")` for a caller that wants units and +never members: it walks the unit table alone and sorts nothing, where +`workspace_symbols("")` walks every member of every unit and sorts the lot. +Measured on opentitan: **15 ms per call**, on every snapshot, gone. + +### `vlog_parser` — `LineIndex::utf16_position` + +```rust +pub fn utf16_position(&self, text: &str, offset: u32) -> (u32, u32); +``` + +The byte-offset → (0-based line, UTF-16 column) conversion, moved down beside +the table it reads so that **two callers cannot disagree**: the semantic index +recording a declaration's position while a file is scanned, and +`lucisv_server::convert::Positions::position` converting a span for the wire. +`Positions::position` is now a two-line wrapper over it and its whole existing +test suite passed unmodified. Pinned across the crate boundary by +`design_hierarchy::tests::an_indexed_position_is_the_position_the_wire_converter_would_have_given`. + +### `lucisv_server::state` — `Document::facts` + +`FileFacts::from_analysis` grew a `src: &str` parameter, because a client +position cannot be read off a line table alone. Its one real caller +(`Document::facts`) already holds that text; the change is a straight +substitution. + +### The wire — `lucisv/moduleHierarchy`, schema 2 + +```json +{ + "schemaVersion": 2, + "revision": 42, + "complete": true, + "files": ["file:///w/top.sv", "file:///w/fifo.sv"], + "modules": [ + { + "moduleName": "top", + "definition": { "file": 0, "range": [0,0,12,9], "selectionRange": [0,7,0,10] }, + "instances": [ + { "instanceName": "u_fifo", "moduleName": "fifo", + "site": { "file": 0, "range": [3,2,3,20], "selectionRange": [3,7,3,13] } } + ] + } + ] +} +``` + +A range is `[startLine, startCharacter, endLine, endCharacter]` — an LSP +`Range` with its four field names left off. `range` covers the whole construct, +`selectionRange` its name, exactly the call-hierarchy contract. Modules and +instances are sorted on the server for deterministic protocol tests and sorted +again defensively in the client. + +Four things left the wire deliberately, and the client rebuilds all four in +`hierarchyModel.js`'s `validateSnapshot` — see the work log for why: + +| gone from the wire | rebuilt as | +|---|---| +| a `uri` on every location | an index into `files` | +| `{ start: { line, character }, end: … }` | four numbers | +| an `id` on every row | `` `${uri}#${line}:${character}` `` of its selection range | +| `definitions` copied onto every instance | the modules of that name, from the client's own table | + +`lucisv/moduleHierarchyChanged { "revision": n }` still rides beside the +server's existing code-lens refresh point, so every index-mutation path is +covered once, and is still gated on `initializationOptions.hierarchyView` so no +other LSP client sees unsolicited traffic. A `-32601` from an older binary +renders a compatibility message and leaves every other extension feature +working. + +### `complete` — what it promises, and the window it has to be honest about + +`complete` is `Server::index_is_complete()`, which is `!scanning && +!must_wait()`. Both clauses, not just `scanning`: `!scanning` alone answers "is +a scan running *this instant*", and a snapshot taken between a finished scan and +a rescan already asked for would call a stale index complete. + +Today that window is unreachable, for two independent reasons, and the second +clause is written down anyway so the flag's honesty does not depend on either: + +1. `rescan_wanted` is only ever **set while `scanning` is true**, and is + consumed inside the scan loop before `scanning` goes false. +2. `must_wait()` sets any request aside — held, unanswered — while + `answering_a_rescan` or `rescan_wanted` is set or anything is already + `held`. A snapshot therefore only ever *reaches* the flag with all three + clear. So `complete` is false exactly during the startup scan, which is the + one scan nothing asked for. + +Pinned by `server::tests::a_snapshot_is_never_answered_complete_while_a_rescan_is_owed`, +which asserts both halves: the flag is false with a rescan owed, and the request +is held rather than answered off the stale index. + +## Status / TODO + +- [x] `InstanceOccurrence` on the statement edge, populated through the shared + instantiation walk; call hierarchy and code lenses unchanged. +- [x] `Def::decl_span`, so a module's whole-construct range needs no reparse. +- [x] `DeclPositions` on `DeclLines` for file-scope declarations, and + `Utf16Range` on every instance occurrence — the snapshot's zero-I/O fix. +- [x] `LineIndex::utf16_position`, shared by the index and the wire converter. +- [x] `WorkspaceIndex::units_of`, so a snapshot does not walk every member. +- [x] Record codec: all of the above in `FACTS_FORMAT` 5, with round-trip and + old-format-rejection tests. +- [x] `lucisv/moduleHierarchy` + `lucisv/moduleHierarchyChanged`, gated on + `initializationOptions.hierarchyView`. +- [x] Schema 2: file table, four-number ranges, no ids, no per-instance + definition copies — 11.6 MB → 2.3 MB on opentitan. +- [x] `complete` tightened to `index_is_complete()` and written down. +- [x] Client: flat resident model, lazy tree levels, prebuilt search index. +- [x] Owner 2026-08-29: hover source preview removed. +- [x] Owner 2026-08-29: every level collapsed by default. +- [x] Owner 2026-08-29: search runs in memory, debounced, capped, and never + re-requests or rebuilds. +- [x] `cargo fmt` / `cargo clippy --all-targets` / `cargo test --workspace`, and + all four node scripts. +- [ ] **Not done, deliberately: `locate::location` is not rewired onto + `DeclPositions`.** `textDocument/definition`, references, the lens and + both hierarchies still read a file to convert a `Def`'s span to a + `Location`, and every unit's range is now in the index for free. It is a + real second consumer and a real saving, and it is a different change to a + different feature's file — filed, not smuggled in. +- [ ] **Not done: members carry no client positions.** See Handshakes for the + cost that decided it; a port-oriented caller would add them to the `M` + group. +- [ ] Manual extension-host acceptance: themes, keyboard-only navigation, zoom, + screen-reader labels, an empty workspace, an old server binary, and both + universal and platform VSIX builds. + +## Work log + +### 2026-08-29 — codex (implementer of the feature) + +The feature itself — the plan, the semantic facts, the custom request and +notification, the webview shell, navigation, the context menu, the bookmark, the +`FACTS_FORMAT` 4 → 5 bump and the committed node tests — was designed and built +by **codex** in this worktree on branch `codex/vscode-hierarchy-sidebar-plan` +from base commit `40094c4`. Everything below is a fix round on top of that work; +the shape of the feature, the flat-snapshot decision, the one-edge-per-statement +decision and the client module split are codex's and are unchanged. + +### 2026-08-29 — dev (snapshot cost, `complete`, and three owner items) + +**The lead's finding, reproduced first.** `snapshot()` read **every** +module-declaring file and built a `LineIndex` over each, per request, and the +client re-pulls on every index change. Over stdio against +`/Users/guoliangchen/repo/opentitan` (3 979 SV files, workspace scope, warm +store, `--release`, `--verbose` so the server times its own handler): + +| | before | after | +|---|---:|---:| +| `lucisv/moduleHierarchy`, server-side handler, first | 197 ms | **34 ms** | +| — settled (the number that blocks the queue) | 145–167 ms | **17–20 ms** | +| — end to end over stdio, settled | 265–325 ms | **39–44 ms** | +| a `textDocument/definition` pipelined behind a snapshot | 263 ms | **41 ms** | +| a `didSave` plus the snapshot the client re-pulls | 366 ms | **141 ms** | +| the response itself | 11 559 498 B | **2 335 749 B** | + +The requirement was ≤ ~20 ms warm; the settled handler is 17–20 ms, and no +snapshot reads a file at any point. + +**(a), not (b), and the measurement says why.** Option (b) — a per-file +snapshot-fragment cache — would have made a *save* cheap and left the first +snapshot of every session paying the whole read (5.0 s cold on the lead's +measurement), and every rescan would have emptied it again. Option (a) makes +**every** snapshot zero-I/O, cold and warm alike, permanently. It is also the +cheaper thing to own: no cache, no invalidation points to keep in step with +`FileView`'s. So (a), and (b) was not needed. + +**But (a) alone did not reach the target, and the measurement said so.** +With the reads gone the handler was still 92–130 ms. Instrumented, it split +three ways: `workspace_symbols("")` 15 ms, building the answer 9 ms, and +**~75 ms of JSON for an 11.6 MB response**. The I/O was never the whole bill. +So two more things had to happen, and both are named in the numbers above: + +- `WorkspaceIndex::units_of` — the snapshot wanted 1 544 modules and was being + handed every declaration in the workspace, sorted. +- **Schema 2.** A `file:///…` URI was written 15 432 times, a range was four + nested objects with eight field names, every row carried an id built from that + same URI, and every instance carried a full copy of the declarations its type + resolves to. All four are redundant with something the client already has, and + the client rebuilds all four in `validateSnapshot` — so the *model* every + other line of client code reads is byte-for-byte the shape codex designed. + 11.6 MB → 2.3 MB. This is the one place the brief's "keep codex's wire shape" + was overridden, and the measurement is the reason: at 11.6 MB the ≤20 ms + requirement is arithmetically out of reach. + +**Store growth, measured both ways.** The client positions are the part this +round added: + +| store | codex's format 5 | this round | delta | +|---|---:|---:|---:| +| 820-file corpus, workspace scope | 2 519 198 B | 2 561 773 B | **+42 575 B, +1.69 %** | +| opentitan, 3 979 files | 24 663 087 B | 25 122 252 B | **+459 165 B, +1.86 %** | + +And against `master`'s format 4 for the whole of format 5 (codex's `decl_span` +plus occurrences, plus this round's positions), on the in-tree 860-file corpus +probe: **2 380 790 B → 2 593 082 B, +212 292 B / +8.9 %**. Scan times over that +corpus are inside their own noise (351 ms cacheless / 377 cold / 205 warm, +against the 350 / 374 / 200 the previous round recorded). This is what the +units-only decision bought: giving every declaration its positions would have +put the growth two orders of magnitude higher on the member count alone. + +**One conversion function, not two.** The dangerous part of carrying positions +in the index is that the index's answer and the wire's could drift — a UTF-16 +column is exactly the kind of thing two implementations get differently on a +CRLF line or a surrogate pair. So the conversion moved down into +`vlog_parser::LineIndex::utf16_position` and `convert::Positions::position` +became a wrapper over it; `convert`'s existing test suite passed unmodified, +and a cross-crate test now requires the index's recorded ranges to equal the +wire converter's over CRLF, two-, three- and four-byte characters, a name on a +last line with no trailing newline, and two instances in one statement. + +**`complete`, tightened and written down** — both, because the brief allowed +either. `index_is_complete()` is `!scanning && !must_wait()`; the second clause +is unreachable today for two independent reasons (`rescan_wanted` is only set +while `scanning`, and `must_wait` holds any request owed a rescan), both spelled +out in Handshakes and pinned by a test that asserts the flag *and* the holding. + +**The v4-store discard path covers format 5, confirmed.** +`index_cache`'s `a_store_from_any_previous_facts_format_is_dropped_not_misread` +loops `1..FACTS_FORMAT`, so it already discards a format-4 store by the header — +it was rewritten away from a pinned literal in the `hover-line-index` round for +exactly this. Its belt-and-braces half, though, had gone stale: its stripper +produced a record that was neither format 3 nor 4, so the test passed for the +wrong reason. Rewritten as `as_a_format_4_record`, which removes all three of +format 5's additions and yields the record format 4 genuinely wrote (verified by +hand against the encoded fixture); `decode` still returns `None`. +`vlog_semantic`'s two generalized strippers were corrected for the new field +widths in the same way. + +#### Owner item 1 (2026-08-29) — the hover source preview is gone + +Removed entirely: `HierarchyView.preview`, the `hover` message, the +`schedulePreview`/`showPreview`/`hidePreview` triplet and the `mouseenter`/ +`mouseleave` listeners in the webview, the `#preview` element and its CSS. It +was **the last consumer of file text in the whole feature**: with it gone the +extension host opens a document only when the user navigates to one, and the +snapshot's zero-I/O property is now the whole story rather than half of it. The +view test asserts positively that a `hover` message posts nothing back and that +the popover is gone from the markup, so the code cannot quietly return. + +#### Owner item 2 (2026-08-29) — every level collapsed by default + +The webview used to expand every root whenever nothing was expanded; that is +gone. This is a `WebviewView`, not a `TreeDataProvider`, so the equivalent of +`collapsibleState: Collapsed` is that the host's `expanded` set starts empty and +only a user `toggle` adds to it. Two expansions survive, and both are the user's +own act rather than a default: the ancestor chain of a **bookmarked** row (the +feature's stated contract — bookmarking reveals) and, while a query is active, +nothing at all, because search now renders a flat list instead of a filtered +tree. + +**Expansion state across a refresh — verified.** A row id is +`root:#:` for a module and `>#:` +per level below, composed in the client from the location itself. It does not +depend on array order, on a `FileId`, or on byte offsets, so a rescan that adds +or removes files elsewhere leaves every unaffected row's id identical and the +open rows stay open. Pinned by +`hierarchyModel_test.js::rowIdsSurviveARefresh`, which reverses the module order +in a second snapshot and requires the same ids and the same opened rows. + +#### Owner item 3 (2026-08-29) — the search freeze, diagnosed and fixed + +**The mechanism, named.** It was not a per-keystroke server request, and it was +not unbounded rendering alone. It was three things compounding, all synchronous +on the extension host and then again on the webview thread: + +1. **`buildHierarchy` materialized the entire expanded tree** the moment a + snapshot arrived. `instanceNode` recursed into its target module's instances, + so a module instantiated in ten places duplicated its whole subtree ten + times. On a real design that is combinatorial in depth — opentitan's 1 544 + modules and 13 888 instances expand to far more nodes than there are + instances. +2. **Every keystroke walked that whole tree.** `search` was posted on the raw + `input` event with **no debounce**; the host ran `filteredHierarchy`, which + visited every node and called `fuzzyScore` twice per node, each call + `toLowerCase()`-ing a name — one allocation per node per keystroke. +3. **Every keystroke then shipped the whole tree to the webview.** + `render()` posted `roots: model.roots.map(serializeNode)` — a deep copy of + every node, structured-cloned across the webview boundary — and the webview + rebuilt its `nodes` map and re-created DOM for everything visible, with no + cap. + +**The fix, against each of the three.** + +1. *Resident and flat.* `buildHierarchy` now keeps exactly the snapshot — + modules and their instances — plus a resolved `targetId` per instance and a + reachability pass over the **module** graph (one visit per module) to pick + roots. A tree row is built only when its parent is open: `treeRows(model, + expanded)` walks roots and descends only into expanded ids. A collapsed tree + over 100 000 instances is one row per root and costs **0.02 ms**. +2. *One prebuilt index, scanned once per query.* `searchIndex` builds one entry + per module and per instance at snapshot time, each carrying its two names + **already lowercased** and two character bit sets. A query lowercases and + splits itself once, then makes one pass: an entry whose bits do not cover the + query's cannot contain the query's characters and is never scored at all. + The top rows are found by **counting hits per score and walking down from the + top** rather than sorting — a one-letter query matches nearly every name, and + sorting 100 000 hits to show 200 of them was most of a frame by itself. Ties + break by index order, which is modules alphabetically and then instances + alphabetically, so the answer is deterministic without comparing any strings. + Input is debounced 60 ms in the webview. +3. *Only the rows shown cross the boundary.* The host posts a flat `rows` array + — the open part of the tree, or one capped page of results — never a tree. + The webview keeps two containers and a query swaps which is shown, so + searching never tears the tree down and clearing the search puts back exactly + the rows that were open, with no snapshot re-request. Results are capped at + 200 with an `N more matches — narrow the search.` line. + +**Before and after, on the generated fixture the node suite now carries** +(20 000 modules × 5 instances = 120 000 search entries, ~6× opentitan): + +| | before | after | +|---|---:|---:| +| build the model from a snapshot | did not finish — the expanded tree is unbounded | 183 ms, once per revision | +| the collapsed tree's rows | (whole tree) | 0.02 ms | +| `u` (matches all 100 000 instances) | — | 3.0 ms | +| `u_inst` | — | 4.4 ms | +| `u_inst_1` (73 756 matches) | — | 8.2 ms | +| `mod_999` (444 matches) | — | 5.6 ms | +| `zzz` (no match) | — | 0.8 ms | + +The owner asked for "microsecond level". Per entry that is what an array scan +gives — 3.0 ms over 120 000 entries is **25 ns each**; per *query* the honest +equivalent at that size is single-digit milliseconds, which is what the table +shows and what `searchOverAHugeHierarchyStaysInsideItsBudget` asserts. The +assertion itself is 60 ms, an order of magnitude of headroom, so a busy machine +cannot make a test that is about orders of magnitude flake. + +**One behaviour changed as a consequence, and it is worth naming.** Codex's plan +had search *filter the tree*, keeping each match plus its ancestor chain. A flat +model has no one path per instance — an instance reached through three different +parents is one row, not three — so search now renders a ranked, capped result +list, each row saying which module writes it, and clicking navigates. The two +context actions that need a path (Copy Full Path, Highlight/Bookmark) stay +tree-only and say so when invoked from a result; Show Definition, Show Instance +and Open on the Right work from either. This is the shape the owner's +"cap rendered results with a N more… affordance" asks for. + +**Files touched.** `crates/vlog_parser/src/line_index.rs`, +`crates/vlog_semantic/src/{workspace.rs,facts.rs,lib.rs}`, +`crates/vlog_semantic/tests/workspace.rs`, +`crates/lucisv_server/src/{design_hierarchy.rs,convert.rs,server.rs,state.rs,index_cache.rs}`, +`editors/vscode/{hierarchyModel.js,hierarchyView.js,hierarchyModel_test.js,hierarchyView_test.js,smoke.js,README.md,CHANGELOG.md}`, +`editors/vscode/media/{hierarchy.js,hierarchy.css}`, this README, +`docs/features/{workspace-index,index-persistence,hover-line-index}/README.md`, +`TOPO.md`, `TODO.md`. No new dependency, no `unsafe`, no `#[allow]`, no +`FACTS_FORMAT` 6, no version bump, no commits. + +**Tests added.** + +| test | where | pins | +|---|---|---| +| `a_file_scope_declaration_carries_its_client_ranges` | `vlog_semantic/tests/workspace.rs` | the extension: a unit's name and decl ranges, 0-based and UTF-16 | +| `client_ranges_count_utf16_units_not_bytes` | same | a four- and a two-byte character ahead of a name shift the client column away from the byte column | +| `every_instance_occurrence_carries_its_client_ranges` | same | both ranges on both instances of one statement | +| `a_member_carries_lines_but_no_client_ranges` | same | the units-only decision, stated as a property | +| `utf16_positions_are_zero_based_and_count_code_units` | `vlog_parser/src/line_index.rs` | surrogate pairs, mid-character flooring, clamping past the end | +| `a_crlf_is_not_part_of_its_lines_utf16_content` | same | the `\r` rule the wire converter has always had | +| `an_indexed_position_is_the_position_the_wire_converter_would_have_given` | `lucisv_server/src/design_hierarchy.rs` | **the round's central safety property**, across the crate boundary, over five awkward shapes | +| `a_snapshot_reads_no_files_at_all` | same | the round's central claim: delete every source file, get a byte-identical snapshot | +| `every_file_is_named_once_and_a_range_is_four_numbers` | same | the file table and the compact range, by counting URI occurrences in the serialized answer | +| `positions_are_zero_based_utf16_even_through_multibyte_text` | same | end to end, through the snapshot | +| `a_snapshot_is_never_answered_complete_while_a_rescan_is_owed` | `lucisv_server/src/server.rs` | the flag is false with a rescan owed, *and* the request is held rather than answered | +| `rootsAreAlphabeticalAndEverythingStartsCollapsed` | `hierarchyModel_test.js` | owner item 2 | +| `openingOneLevelAtATimeWalksTheDesign` | same | lazy levels build the right rows in the right order | +| `rowIdsSurviveARefresh` | same | expansion state across a rescan, by reversing module order | +| `bookmarksResolveByPathWithoutATableOfEveryPath` | same | the bookmark walks down instead of consulting a table of every path | +| `searchScansTheFlatIndexAndKeepsAncestorContext` | same | one row per instance, names only, and what a result navigates to | +| `theNarrowWireIsRebuiltIntoTheWideModel` | same | schema 2 → the model codex's client code reads | +| `searchOverAHugeHierarchyStaysInsideItsBudget` | same | owner item 3's budget, on a generated 120 000-entry fixture | +| the view suite's collapsed/lazy/search/no-preview assertions | `hierarchyView_test.js` | owner items 1–3 through the real provider | + +**Gates.** `cargo fmt --all -- --check` clean. `cargo clippy --all-targets +--workspace` silent. `cargo test --workspace` green, 0 failed — +`lucisv_server` unit tests 1 297 passed / 33 ignored, its `e2e` suite 63 passed +/ 2 ignored, `vlog_semantic`'s `workspace` suite 77 passed. All four node +scripts OK: `hierarchyModel_test.js`, `hierarchyView_test.js`, +`restart_test.js` (44 checks), `smoke.js`. + +## QA log + +### 2026-08-29 — QA (adversarial pass on the dev round) + +**Scope note first.** `git diff master` over-reports this round's footprint: +`master` has advanced two commits past this branch's own base (`40094c4`, +`37560ca` and a `--stdio` hotfix), so a plain diff against `master` makes it +look like `server.rs`/`state.rs` dropped +`a_widen_that_subsumes_the_old_scope_reads_only_the_files_it_adds` and its +doc comment. They did not — that test was added by `37560ca`, a commit this +branch never had. `git diff HEAD` (this branch's own tip) is the correct +diff and shows only this round's real changes; verified with +`git merge-base HEAD master` = `40094c4`. + +**Verdict: SHIP.** No corruption, no idempotency break, no widened +`verify.rs` forgiveness, nothing dropped silently. One real finding, low +severity, everything else confirmed by hand or by new regression tests. + +**1. Position agreement (adversarial extension) — confirmed, no divergence.** +Extended `an_indexed_position_is_the_position_the_wire_converter_would_have_given` +(`crates/lucisv_server/src/design_hierarchy.rs:344`) with two more hostile +shapes: CRLF and bare LF mixed in one file, and an instance on the same +source line as its module header. Both agree with `convert::Positions` +exactly, as every other shape already did. Raised the fixture's own +`checked >= 11` premise to `>= 16` to keep counting honest against the two +new sources. `cargo test -p lucisv_server design_hierarchy::` — 8/8 pass. + +**2. Schema-2 fidelity on a hostile workspace — confirmed, no bug; coverage +was missing and is now filled.** The client-side rebuild +(`theNarrowWireIsRebuiltIntoTheWideModel`, +`editors/vscode/hierarchyModel_test.js:204`) is a real check against a +hand-built wire fixture, not a self-reference — it does not call the server +or reuse `buildHierarchy`'s own output as its oracle. But nothing on the +*server* side had ever produced a wire snapshot from duplicate module +names, an escaped identifier, or a module with many instances of another — +exactly the hostile shapes the charter named. Added three tests to +`design_hierarchy.rs`: +- `duplicate_module_names_across_files_stay_two_distinct_rows` — two files + each declaring `module dup`; the wire keeps two separate rows keyed by + `(file, definition range)`, each with only its own file's instances. +- `an_escaped_identifier_names_a_module_and_an_instance` — `\weird$leaf ` and + `\u$inst ` (space-terminated, space not part of the name) round-trip + through the wire unmangled. +- `one_hundred_instances_of_one_module_are_one_hundred_sorted_rows` — caught + a bug in my *own* first draft, not the feature's: the fixture generator + wrote `leaf u_000 (), leaf u_001 (), …` (repeating the module keyword per + instance, invalid Verilog), which the parser silently produced zero + instances for. Fixed to `leaf u_000 (), u_001 (), …, u_099 ();` (one + module, 100 comma-separated instances); all 100 came back as sorted, + individual rows. Filed here as a QA-harness bug, not a feature bug — the + server encoder was never wrong. + +**3. Format-5 discipline — confirmed by hand.** Walked the `as_a_format_4_record` +field-stripper (`crates/lucisv_server/src/index_cache.rs:600`) against the +actual encoder field order in `facts.rs` by counting fields myself: a unit's +group is `name, kind, name_span×2, decl_span×2, detail_span×2, lines×2` (10 +fields) then `positions` (2 `Utf16Range`s × 4 = 8 fields) = 18, and an +instantiation's occurrence is `name, name_span×2, span×2, name_positions×4, +positions×4` = 13 fields behind its own count field. The two `drain` calls +remove exactly those, in descending index order so neither shifts the +other's target before it runs — `as_a_format_4_record` really does yield +what format 4 wrote, not a fabricated shape that merely fails to decode for +some other reason. `cargo test` confirms `a_format_4_record_without_instance_occurrences_is_rejected` +and the belt-and-braces assertion both still pass. + +**4. Search honesty — confirmed by hand, previously untested at this +precision; two regression tests added to `hierarchyModel_test.js`.** +- `topKSearchMatchesWhatAFullSortWouldChoose` — five instances of one + module scored against `fifo` by the documented rule (exact/prefix/ + substring/subsequence tiers, arithmetic shown in the test's own comment); + asserts the counting cutoff's capped-at-3 answer is `["fifo", "fifo_ctrl", + "ffifo"]` in that order with `truncated: 2`, and that an uncapped call + returns all five in the same relative order. This is the "same top + results a full sort would give" check the charter asked for; nothing like + it existed before (the 120k-entry budget test only measures speed and a + cap that is tautologically consistent with its own `truncated` field). +- `theBitmaskPrefilterNeverExcludesATrueSubsequenceMatch` — an independent, + un-bitmasked `isSubsequence` checker (does not call `maskOf`) confirms six + adversarial (haystack, needle) pairs really are subsequence matches, + including escaped-identifier-shaped names with `$`, `.` and `[]` (all of + which fold onto the same "other" bit in `maskOf`'s coarse classification), + then asserts `fuzzyScore` and `searchHierarchy` both find them too. By + construction (every character sets some bit, and the "other" bucket can + only make the prefilter more permissive, never less) this class of bug is + not reachable, but it was previously asserted nowhere. +- The existing 120k-entry fixture's `N more matches` check + (`found.truncated === found.total - SEARCH_LIMIT`) is real but narrower + than it looks: `truncated` is *defined* as `total - rows.length`, so the + assertion is actually pinning `rows.length === SEARCH_LIMIT` exactly when + over the cap, not independently verifying `total`'s own correctness. Not a + bug — `total` comes from the same counting pass the charter already asked + me to hand-verify above — but worth recording so a future reader does not + mistake it for a hand-checked "right N". + +**5. Complete/held semantics — confirmed as documented, not independently +re-driven through the widen machinery.** +`a_snapshot_is_never_answered_complete_while_a_rescan_is_owed` +(`server.rs:5523`) sets `rescan_wanted = true` directly rather than +triggering a real scope widen, but `rescan_wanted` is exactly, and only, the +flag every real widen path sets (`server.rs:1833,1870,1927`, all three +verified by inspection) before `must_wait` holds the request — so the test +exercises the true mechanism, not a stand-in for it. Did not add a +heavier end-to-end "trigger a real widen, then race a snapshot against it" +test; diminishing returns against the direct flag test already there. + +**6. Perf reproduction — independently reproduced on +`/Users/guoliangchen/repo/opentitan`, matches the claimed numbers closely.** +Built `--release`, drove a hand-rolled LSP client over stdio (workspace +scope pulled via `workspace/configuration`, `--verbose` for server-side +handler timing), no test dependency. Settled: +- 1 544 modules (README claims 1 544 — exact match). +- Snapshot 2 335 713 B (README: 2 335 749 B on its own run — 36 B apart, + consistent with ordinary opentitan corpus drift between runs). +- Server-reported handler time settled at 16.3–17.98 ms across two runs + (README: 17–20 ms — inside range, in fact slightly faster). +- Client round trip over stdio settled at 29.9–36.7 ms (README's "end to + end… settled" is 39–44 ms; this machine is somewhat faster end to end, + same order of magnitude, same conclusion: no file is read per snapshot). +- First request after the real workspace-scope index landed (the + cold/rescan-blocked one) took 1.2–3.1 s across two runs — consistent with + "a request pipelined behind a rescan waits for the rescan," not a + regression, since the round only claims the *settled* number. +Did not separately reproduce the `didSave`-plus-re-pull ~141 ms figure +(would need a second harness pass simulating an editor save); the settled +snapshot and rescan-blocked numbers above exercise the same code paths that +number is built from. + +**7. Full gates — all green, including new tests.** +- `cargo fmt --all -- --check` clean (after `cargo fmt` on my own new test + code). +- `cargo clippy --all-targets --workspace` silent. +- `cargo test --workspace`: 0 failed. `lucisv_server` unit tests + 1 300 passed / 33 ignored (1 297 + 3 new design_hierarchy tests), `e2e` + 63 passed / 2 ignored, `vlog_semantic` `workspace` suite 77 passed — + matching the work log's counts plus my additions. +- `hierarchyModel_test.js`, `hierarchyView_test.js`, `restart_test.js` + (44 checks), `smoke.js` (against a `--release` build) — all OK. + +**Tests added this pass.** + +| test | where | pins | +|---|---|---| +| two new sources in `an_indexed_position_is_the_position_the_wire_converter_would_have_given` | `design_hierarchy.rs` | CRLF+LF mixed in one file; instance on the module header's own line | +| `duplicate_module_names_across_files_stay_two_distinct_rows` | same | two `module dup` declarations stay two wire rows, never merged | +| `an_escaped_identifier_names_a_module_and_an_instance` | same | `\weird$leaf `/`\u$inst ` round-trip the wire unmangled | +| `one_hundred_instances_of_one_module_are_one_hundred_sorted_rows` | same | 100 instances of one statement are 100 sorted rows | +| `topKSearchMatchesWhatAFullSortWouldChoose` | `hierarchyModel_test.js` | the counting cutoff picks the same top-K a full sort would, checked by hand | +| `theBitmaskPrefilterNeverExcludesATrueSubsequenceMatch` | same | an independent, un-bitmasked subsequence check against escaped-identifier-shaped names | + +**Findings.** + +| severity | finding | +|---|---| +| low (harness/process, not code) | `git diff master` on this worktree conflates two unrelated upstream commits with this round's own changes; use `git diff HEAD` (`merge-base HEAD master` = `40094c4`, this branch's own base) — flagged so the lead doesn't review a phantom deletion of `a_widen_that_subsumes_the_old_scope_reads_only_the_files_it_adds`. | +| informational | The 120k-entry `N more matches` assertion is tautologically tied to its own `total`/`rows.length` definitions rather than an independent oracle; not wrong, now supplemented by a hand-checked small fixture (finding 4 above). | +| informational | `complete`/`must_wait` is pinned via a direct flag set rather than a live-triggered widen; the flag is the real mechanism's own signal, so this is a documentation note, not a gap requiring more test weight. | + +No masked-corruption risk, no `verify.rs` change, no `unsafe`, no new +dependency, no `FACTS_FORMAT` 6, no commits made. + +## Review + +**2026-08-29 — lead.** Reviewed across the whole arc: codex's +implementation (externally contributed; UI architecture and the +flat-snapshot/client-tree split were right from the start), the lead's +own QA pass that measured the 5 s / 300 ms-per-save snapshot cost, the +fix round (index-carried positions folded into the format 5 codex was +already minting — one bump, not two; schema 2 forced by arithmetic, +with codex's client model rebuilt byte-for-byte behind validateSnapshot), +the owner's three UI rulings (preview removed, collapsed by default, +resident-model search with the freeze diagnosed three ways), and QA's +SHIP with independent oracles added where the round's own tests were +self-consistent. Gates re-run by the lead on the worktree. The wire +break from codex's schema 1 is accepted: no shipped client ever spoke +it, and the model layer preserves the contract where code actually +reads it. Search-as-ranked-list instead of filtered tree is accepted +as the necessary consequence of the flat model the owner asked for, +with the tree-only actions honestly labeled. The --stdio hotfix is +mirrored here and merges clean with master's. Accepted; merged by the +lead. Credit: codex (implementation), Opus dev (integration fixes), +Sonnet QA, the owner's live UI feedback. + +_(reserved for the lead.)_ diff --git a/docs/features/workspace-index/README.md b/docs/features/workspace-index/README.md index 1e7d86d..866766b 100644 --- a/docs/features/workspace-index/README.md +++ b/docs/features/workspace-index/README.md @@ -41,13 +41,24 @@ impl WorkspaceIndex { fn fingerprint(&self) -> String; // 2026-08-27 fn find_define(&self, name: &str) -> Vec<(FileId, &Define)>; fn workspace_symbols(&self, query: &str) -> Vec>; + fn units_of(&self, SymbolKind) -> impl Iterator; // 2026-08-29 fn counts(&self) -> IndexCounts; } -struct Def { file: FileId, name_span: TextRange, kind: SymbolKind, +struct Def { file: FileId, name_span: TextRange, decl_span: TextRange, // 2026-08-29, hierarchy sidebar + 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 DeclLines { name: u32, detail: Option, // 1-based source lines + positions: Option } // 2026-08-29, hierarchy sidebar +// Where a *file-scope* declaration sits as a client counts positions, so an +// editor can be pointed at a module in a closed file with no read at all. +// `None` for a member: members outnumber units by two orders of magnitude and +// nothing wants theirs, and the record's `U` and `M` groups are separate, so a +// member spends no field on the absence. +struct DeclPositions { name: Utf16Range, decl: Utf16Range } +struct Utf16Range { start: Utf16Pos, end: Utf16Pos } +struct Utf16Pos { line: u32, character: u32 } // 0-based line, UTF-16 units struct WorkspaceSymbol<'a> { name: &'a str, container: Option<&'a str>, def: &'a Def } struct IndexCounts { files, modules, packages, typedefs, members, defines } diff --git a/editors/vscode/.vscodeignore b/editors/vscode/.vscodeignore index d632a11..110304b 100644 --- a/editors/vscode/.vscodeignore +++ b/editors/vscode/.vscodeignore @@ -2,5 +2,7 @@ # extension. `restart.js` itself IS shipped — `extension.js` requires it. smoke.js restart_test.js +hierarchyModel_test.js +hierarchyView_test.js .vscode/** .gitignore diff --git a/editors/vscode/CHANGELOG.md b/editors/vscode/CHANGELOG.md index 95e1d86..f25ec97 100644 --- a/editors/vscode/CHANGELOG.md +++ b/editors/vscode/CHANGELOG.md @@ -5,6 +5,26 @@ for you. The extension and its bundled language server share one version number; the full engineering notes live in the [project changelog](https://git.luci.ooo/lucio/lucisv/src/branch/master/CHANGELOG.md). +## Unreleased + +- Added a dedicated **lucisv Hierarchy** Activity Bar view with a persistent + fuzzy search field for module and instance names, alphabetical instance + paths, exact source navigation, full-path copy, definition/instance actions, + yellow workspace bookmarks, and split-right definition opening. +- Every level of the hierarchy starts collapsed; nothing expands on its own, + and what you open stays open across a refresh or a rescan. +- Searching the hierarchy runs entirely in memory over a prebuilt name index: + it never asks the server per keystroke and never rebuilds the tree. Results + are ranked and capped, with a count of the matches not shown. +- The workspace index now retains each individual instance name and source + span while preserving the existing statement-level call-hierarchy and code- + lens counts, and it records the editor positions of every module declaration + and instance — so the hierarchy snapshot reads no files at all. On a + 4 000-file workspace the snapshot went from ~300 ms and 11.6 MB to ~40 ms + and 2.3 MB, and a go-to-definition sent behind one no longer waits a + quarter of a second. The index cache rebuilds once because its facts format + changed. + ## 0.14.0 — 2026-08-28 The first-hover release. diff --git a/editors/vscode/README.md b/editors/vscode/README.md index 3010ac2..f6d873f 100644 --- a/editors/vscode/README.md +++ b/editors/vscode/README.md @@ -60,6 +60,9 @@ way the extension finds them and makes them executable on first activation. Most features work as soon as a supported file opens: +- Open the **lucisv** Activity Bar icon for an instance-oriented design tree. + Every level starts collapsed; its fixed search field fuzzy-matches module and + instance names in memory, and click or the instance context menu navigates. - Hover a symbol, press `F12`, find references, search workspace symbols, or open the call/type hierarchy using VS Code's standard commands. - Type a module name at module-item scope to insert a complete instance. Inside @@ -130,6 +133,7 @@ enabling both paths formats twice. | Inlay hints | Adds port and parameter names to ordered instantiations without guessing at ambiguous sites | | Code lenses | Shows the workspace-wide instantiation count above every module/interface; click to jump to a site | | Call hierarchy | Incoming calls answer “who instantiates this?”; outgoing calls answer “what does this instantiate?” | +| Design hierarchy sidebar | Alphabetical instance paths from every top-level module, collapsed until you open them, in-memory fuzzy module/instance search, exact instance/definition jumps, path copy, bookmark highlighting, and split-right opening | | Type hierarchy | Walks class `extends` relationships to supertypes and workspace subtypes | ### Highlighting and presentation diff --git a/editors/vscode/extension.js b/editors/vscode/extension.js index 521368f..9cc055a 100644 --- a/editors/vscode/extension.js +++ b/editors/vscode/extension.js @@ -13,6 +13,7 @@ const path = require('path'); const vscode = require('vscode'); const { LanguageClient, ProposedFeatures, TransportKind } = require('vscode-languageclient/node'); const { createRestarter } = require('./restart'); +const { HierarchyView } = require('./hierarchyView'); /** The single client, kept only so `deactivate` can stop it. */ let client; @@ -23,6 +24,9 @@ let client; */ let restarter; +/** The instance-oriented design hierarchy hosted in lucisv's sidebar. */ +let hierarchyView; + /** The languages this extension attaches to. */ const LANGUAGES = ['verilog', 'systemverilog']; @@ -179,6 +183,9 @@ function activate(context) { // neither reaches it, and to no cache at all if it cannot work one out. initializationOptions: { storagePath: (context.storageUri || context.globalStorageUri || {}).fsPath, + // Opt into the custom invalidation notification. Other LSP clients can + // still request a snapshot, but receive no unsolicited lucisv traffic. + hierarchyView: true, }, }; @@ -193,12 +200,17 @@ function activate(context) { client.registerFeatures(ProposedFeatures.createAll(client)); context.subscriptions.push(client); + hierarchyView = new HierarchyView(context, client); + // Built before anything can ask it for a restart — the settings listener // below calls it, and nothing may reach that listener with this unset. restarter = createRestarter({ client, serverOptions, - onStarted: repaintVisible, + onStarted: () => { + repaintVisible(); + hierarchyView.onStarted(); + }, onStartFailed: reportStartFailure, }); diff --git a/editors/vscode/hierarchyModel.js b/editors/vscode/hierarchyModel.js new file mode 100644 index 0000000..a1903cb --- /dev/null +++ b/editors/vscode/hierarchyModel.js @@ -0,0 +1,574 @@ +// Pure model for the lucisv hierarchy webview. No VS Code dependency: the +// graph, sorting, fuzzy matching and bookmark rules are driven by plain Node +// tests and the extension host only performs I/O/navigation. +// +// **The hierarchy is held flat and expanded lazily.** The first shape of this +// file materialized every path of the whole design the moment a snapshot +// arrived — a module instantiated in ten places duplicated its entire subtree +// ten times — and then walked that tree, scored two names per node and shipped +// the whole thing to the webview on *every keystroke*. That is the freeze the +// owner hit (2026-08-29). What is resident now is exactly the snapshot: modules +// and their instances, plus one prebuilt lowercased search index. A tree row is +// built only when the user opens its parent, and a query is answered by one +// pass over the flat index. See +// docs/features/vscode-hierarchy-sidebar/README.md. + +// The wire is deliberately narrow — a file table, four-number ranges, no ids +// and no per-instance definition copies — because the whole design is re-sent +// on every index change and 11.6 MB of it blocked the server's request queue. +// Everything below `validateSnapshot` works on the wide shape +// (`{ uri, range: { start, end }, selectionRange }`, an id per row, a +// `definitions` array per instance), which this file rebuilds once per +// snapshot. +const SCHEMA_VERSION = 2; + +/** How many search rows are rendered before the view says "N more…". */ +const SEARCH_LIMIT = 200; + +/** One `[startLine, startCharacter, endLine, endCharacter]` from the wire. */ +function isWireRange(value) { + return Array.isArray(value) && value.length === 4 + && value.every((n) => Number.isInteger(n) && n >= 0); +} + +function toRange(wire) { + return { + start: { line: wire[0], character: wire[1] }, + end: { line: wire[2], character: wire[3] }, + }; +} + +function isWireLocation(value, files) { + return value && Number.isInteger(value.file) && value.file >= 0 && value.file < files.length + && isWireRange(value.range) && isWireRange(value.selectionRange); +} + +function toLocation(wire, files) { + return { + uri: files[wire.file], + range: toRange(wire.range), + selectionRange: toRange(wire.selectionRange), + }; +} + +/** The row id the server used to send: unique because two declarations cannot + * begin at one position in one file, and stable across refreshes. */ +function idOf(location) { + return `${location.uri}#${location.selectionRange.start.line}:${location.selectionRange.start.character}`; +} + +function locationKey(location) { + const start = location.selectionRange.start; + const end = location.selectionRange.end; + return `${location.uri}|${start.line}:${start.character}-${end.line}:${end.character}`; +} + +function compareText(a, b) { + const foldedA = a.toLowerCase(); + const foldedB = b.toLowerCase(); + if (foldedA < foldedB) return -1; + if (foldedA > foldedB) return 1; + if (a < b) return -1; + if (a > b) return 1; + return 0; +} + +function compareModules(a, b) { + return compareText(a.moduleName, b.moduleName) + || compareText(a.definition.uri, b.definition.uri) + || a.definition.selectionRange.start.line - b.definition.selectionRange.start.line + || a.definition.selectionRange.start.character - b.definition.selectionRange.start.character; +} + +function compareInstances(a, b) { + return compareText(a.instanceName, b.instanceName) + || compareText(a.moduleName, b.moduleName) + || compareText(a.site.uri, b.site.uri) + || a.site.selectionRange.start.line - b.site.selectionRange.start.line + || a.site.selectionRange.start.character - b.site.selectionRange.start.character; +} + +function validateSnapshot(value) { + if (!value || value.schemaVersion !== SCHEMA_VERSION || !Number.isInteger(value.revision) + || typeof value.complete !== 'boolean' || !Array.isArray(value.modules) + || !Array.isArray(value.files) || !value.files.every((uri) => typeof uri === 'string')) { + throw new Error('The language server returned an unsupported hierarchy snapshot.'); + } + const files = value.files; + const ids = new Set(); + const modules = value.modules.map((module) => { + if (!module || typeof module.moduleName !== 'string' || module.moduleName === '' + || !isWireLocation(module.definition, files) || !Array.isArray(module.instances)) { + throw new Error('The language server returned a malformed hierarchy module.'); + } + const definition = toLocation(module.definition, files); + const id = idOf(definition); + if (ids.has(id)) throw new Error('The hierarchy snapshot contains a duplicate module id.'); + ids.add(id); + const instances = module.instances.map((instance) => { + if (!instance || typeof instance.instanceName !== 'string' || instance.instanceName === '' + || typeof instance.moduleName !== 'string' || instance.moduleName === '' + || !isWireLocation(instance.site, files)) { + throw new Error('The language server returned a malformed hierarchy instance.'); + } + const site = toLocation(instance.site, files); + return { + id: idOf(site), + instanceName: instance.instanceName, + moduleName: instance.moduleName, + site, + definitions: [], + }; + }); + instances.sort(compareInstances); + return { id, moduleName: module.moduleName, definition, instances }; + }); + modules.sort(compareModules); + + // What the server used to repeat on every instance: the declarations its + // module name resolves to. Every one of them is a module in this same + // snapshot, so the lookup is exact rather than an approximation of it — and + // the answer is deterministic because `modules` is already sorted. + const byName = new Map(); + for (const module of modules) { + const found = byName.get(module.moduleName) || []; + found.push(module.definition); + byName.set(module.moduleName, found); + } + for (const module of modules) { + for (const instance of module.instances) { + instance.definitions = (byName.get(instance.moduleName) || []).slice(); + } + } + return { schemaVersion: SCHEMA_VERSION, revision: value.revision, complete: value.complete, modules }; +} + +function buildHierarchy(raw) { + const snapshot = validateSnapshot(raw); + const byId = new Map(snapshot.modules.map((module) => [module.id, module])); + const moduleAt = new Map(snapshot.modules.map((module) => [ + locationKey(module.definition), module, + ])); + + // An instance resolves to a module exactly when its type names one + // declaration. Resolved once here, not once per render. + for (const module of snapshot.modules) { + for (const instance of module.instances) { + const target = instance.definitions.length === 1 + ? moduleAt.get(locationKey(instance.definitions[0])) + : undefined; + instance.targetId = target ? target.id : undefined; + instance.unresolved = instance.definitions.length === 0; + instance.ambiguous = instance.definitions.length > 1; + } + } + + const parented = new Set(); + for (const module of snapshot.modules) { + for (const instance of module.instances) { + if (instance.targetId) parented.add(instance.targetId); + } + } + + // Reachability over the *module* graph, not over the expanded tree: the + // question "is this module already shown somewhere" needs one visit per + // module, and the expanded tree has no bound. + const reached = new Set(); + function reach(start) { + const stack = [start]; + while (stack.length > 0) { + const module = stack.pop(); + if (reached.has(module.id)) continue; + reached.add(module.id); + for (const instance of module.instances) { + const target = instance.targetId && byId.get(instance.targetId); + if (target) stack.push(target); + } + } + } + + const roots = []; + for (const module of snapshot.modules) { + if (parented.has(module.id)) continue; + roots.push({ module, fallback: false }); + reach(module); + } + // Whatever a root never reaches is inside a recursive component: show it, + // marked, so `A -> B -> A` is visible without an infinite tree. + for (const module of snapshot.modules) { + if (reached.has(module.id)) continue; + roots.push({ module, fallback: true }); + reach(module); + } + + const entries = searchIndex(snapshot.modules); + return { + revision: snapshot.revision, + complete: snapshot.complete, + modules: snapshot.modules, + byId, + roots, + entries, + // Reused per query rather than allocated per keystroke. + scores: new Int32Array(entries.length), + counts: new Int32Array(MAX_SCORE + 1), + }; +} + +/// One flat, prelowered row per module and per instance — built once per +/// snapshot, scanned once per query. Nothing here is per-path: an instance +/// appears once however many times the tree would show it. +function searchIndex(modules) { + const entries = []; + for (const module of modules) { + const lowerModule = module.moduleName.toLowerCase(); + const [moduleLetters, moduleDigits] = maskOf(lowerModule); + entries.push({ + kind: 'module', + module, + instance: undefined, + lowerModule, + lowerInstance: '', + moduleLetters, + moduleDigits, + instanceLetters: 0, + instanceDigits: 0, + }); + for (const instance of module.instances) { + const type = instance.moduleName.toLowerCase(); + const name = instance.instanceName.toLowerCase(); + const [typeLetters, typeDigits] = maskOf(type); + const [nameLetters, nameDigits] = maskOf(name); + entries.push({ + kind: 'instance', + module, + instance, + lowerModule: type, + lowerInstance: name, + moduleLetters: typeLetters, + moduleDigits: typeDigits, + instanceLetters: nameLetters, + instanceDigits: nameDigits, + }); + } + } + return entries; +} + +// A deterministic subsequence score. Higher wins; -1 is no match. The first +// tier keeps the ordering intuitive, the bonuses make `u_f` prefer `u_fifo` +// over a scattered set of the same letters. Both sides are already lowercase, +// and `needle` arrives split into characters: lowercasing and re-splitting per +// call is what made one keystroke allocate once per name in the workspace. +function scoreLower(haystack, needle, chars) { + if (needle === '') return 0; + if (haystack === needle) return 10000; + if (haystack.startsWith(needle)) return 8000 - (haystack.length - needle.length); + const at = haystack.indexOf(needle); + if (at >= 0) return 6000 - at * 10 - (haystack.length - needle.length); + + let cursor = 0; + let score = 0; + let previous = -2; + for (let k = 0; k < chars.length; k += 1) { + const found = haystack.indexOf(chars[k], cursor); + if (found < 0) return -1; + score += 10; + if (found === previous + 1) score += 18; + if (found === 0 || !isWordCharacter(haystack.charCodeAt(found - 1))) score += 12; + score -= found; + previous = found; + cursor = found + 1; + } + return score; +} + +/// `a`–`z` or `0`–`9`, on an already-lowercased string. A character that is +/// neither opens a word, which is where the word-boundary bonus is paid. +function isWordCharacter(code) { + return (code >= 97 && code <= 122) || (code >= 48 && code <= 57); +} + +/// Which characters a name contains, as two bit sets: letters, `_` and +/// "something else" in the first, digits in the second. A subsequence match +/// needs every one of the query's characters to be present, so a name whose +/// bits do not cover the query's cannot match and is never scored — which is +/// what keeps a query that matches almost nothing as cheap as one that matches +/// almost everything. +function maskOf(lower) { + let letters = 0; + let digits = 0; + for (let at = 0; at < lower.length; at += 1) { + const code = lower.charCodeAt(at); + if (code >= 97 && code <= 122) letters |= 1 << (code - 97); + else if (code >= 48 && code <= 57) digits |= 1 << (code - 48); + else if (code === 95) letters |= 1 << 26; + else letters |= 1 << 27; + } + return [letters, digits]; +} + +function fuzzyScore(text, query) { + const needle = query.trim().toLowerCase(); + return scoreLower(text.toLowerCase(), needle, [...needle]); +} + +/// The highest score `scoreLower` can return, plus the instance-name tie-break +/// point. Scores are small non-negative integers, which is what lets the top of +/// a very large result set be found by counting rather than by sorting. +const MAX_SCORE = 10001; + +/// Every entry the query matches, best first, capped at `limit`. +/// +/// **No sort over the whole result set.** A one-letter query matches nearly +/// every name in the workspace, and sorting 100 000 hits to show 200 of them is +/// most of a frame on its own. Scores are bounded integers, so the cutoff is +/// found by counting hits per score and walking down from the top — one extra +/// pass over an array, and only the rows actually shown are ever built. Ties +/// are broken by index order, which is modules alphabetically and then +/// instances alphabetically, so the answer is deterministic without comparing +/// any strings. +function searchHierarchy(model, query, limit = SEARCH_LIMIT) { + const needle = query.trim().toLowerCase(); + if (needle === '') return { rows: [], total: 0, truncated: 0 }; + const entries = model.entries; + const scores = model.scores; + const counts = model.counts; + counts.fill(0); + + const chars = [...needle]; + const [wantLetters, wantDigits] = maskOf(needle); + let total = 0; + for (let at = 0; at < entries.length; at += 1) { + const entry = entries[at]; + let score = -1; + if ((entry.moduleLetters & wantLetters) === wantLetters + && (entry.moduleDigits & wantDigits) === wantDigits) { + score = scoreLower(entry.lowerModule, needle, chars); + } + if (entry.kind === 'instance' + && (entry.instanceLetters & wantLetters) === wantLetters + && (entry.instanceDigits & wantDigits) === wantDigits) { + const own = scoreLower(entry.lowerInstance, needle, chars); + // An instance-name tie wins by one, as the UI contract specifies. + if (own >= 0 && own + 1 > score) score = own + 1; + } + if (score > MAX_SCORE) score = MAX_SCORE; + scores[at] = score; + if (score >= 0) { + counts[score] += 1; + total += 1; + } + } + + // The lowest score that still fits inside `limit`, and how many rows of + // exactly that score may be taken. + let cutoff = 0; + let above = 0; + for (let score = MAX_SCORE; score >= 0; score -= 1) { + if (above + counts[score] >= limit || score === 0) { + cutoff = score; + break; + } + above += counts[score]; + } + let roomAtCutoff = Math.max(0, limit - above); + + const taken = []; + for (let at = 0; at < entries.length && taken.length < limit; at += 1) { + const score = scores[at]; + if (score < cutoff) continue; + if (score === cutoff) { + if (roomAtCutoff === 0) continue; + roomAtCutoff -= 1; + } + taken.push({ at, score }); + } + taken.sort((a, b) => b.score - a.score || a.at - b.at); + const rows = taken.map(({ at }) => searchRow(entries[at])); + return { rows, total, truncated: Math.max(0, total - rows.length) }; +} + +function searchLabel(entry) { + return entry.kind === 'module' + ? entry.module.moduleName + : `${entry.instance.instanceName} (${entry.instance.moduleName})`; +} + +function searchId(entry) { + return entry.kind === 'module' + ? `find:${entry.module.id}` + : `find:${entry.module.id}>${entry.instance.id}`; +} + +function searchRow(entry) { + return { + id: searchId(entry), + kind: entry.kind, + label: searchLabel(entry), + // Where the row lives, since a flat hit has no one path to show. + detail: entry.kind === 'module' ? 'module' : `in ${entry.module.moduleName}`, + depth: 0, + hasChildren: false, + expanded: false, + warning: entry.kind === 'instance' && (entry.instance.unresolved || entry.instance.ambiguous), + }; +} + +/// What a search row points at, for navigation and the context menu. +function searchTarget(model, id) { + if (typeof id !== 'string' || !id.startsWith('find:')) return undefined; + const [moduleId, instanceId] = id.slice('find:'.length).split('>'); + const module = model.byId.get(moduleId); + if (!module) return undefined; + if (instanceId === undefined) { + return { + kind: 'module', + moduleName: module.moduleName, + definition: module.definition, + definitions: [module.definition], + site: undefined, + }; + } + const instance = module.instances.find((candidate) => candidate.id === instanceId); + if (!instance) return undefined; + const target = instance.targetId && model.byId.get(instance.targetId); + return { + kind: 'instance', + moduleName: instance.moduleName, + instanceName: instance.instanceName, + definition: target && target.definition, + definitions: instance.definitions, + site: instance.site, + }; +} + +/// The rows the tree shows: every root, then the children of every row the +/// user has opened. Nothing below a closed row is built at all. +function treeRows(model, expanded, bookmarkPath) { + const rows = []; + const nodes = new Map(); + const bookmarkId = bookmarkPath ? idForPath(model, bookmarkPath) : undefined; + + function push(node) { + nodes.set(node.id, node); + rows.push({ + id: node.id, + kind: node.kind, + label: node.label, + detail: node.detail, + depth: node.depth, + hasChildren: node.hasChildren, + expanded: expanded.has(node.id), + warning: node.warning, + bookmarked: node.id === bookmarkId, + }); + if (!expanded.has(node.id) || !node.hasChildren) return; + for (const child of childrenOf(model, node)) push(child); + } + + for (const { module, fallback } of model.roots) push(rootNode(model, module, fallback)); + return { rows, nodes, bookmarkId }; +} + +function rootNode(model, module, fallback) { + return { + id: `root:${module.id}`, + kind: 'module', + moduleName: module.moduleName, + label: module.moduleName, + detail: fallback ? 'recursive' : '', + depth: 0, + parentId: null, + fullPath: module.moduleName, + hasChildren: module.instances.length > 0, + warning: fallback, + definition: module.definition, + definitions: [module.definition], + site: undefined, + moduleId: module.id, + seen: new Set([module.id]), + }; +} + +function childrenOf(model, node) { + const module = model.byId.get(node.moduleId); + if (!module) return []; + return module.instances.map((instance) => instanceNode(model, node, instance)); +} + +function instanceNode(model, parent, instance) { + const target = instance.targetId && model.byId.get(instance.targetId); + const recursive = Boolean(target && parent.seen.has(target.id)); + const seen = new Set(parent.seen); + if (target) seen.add(target.id); + return { + id: `${parent.id}>${instance.id}`, + kind: 'instance', + moduleName: instance.moduleName, + instanceName: instance.instanceName, + label: `${instance.instanceName} (${instance.moduleName})`, + detail: instance.unresolved ? 'unresolved' + : (instance.ambiguous ? 'ambiguous' : (recursive ? 'recursive' : '')), + depth: parent.depth + 1, + parentId: parent.id, + fullPath: `${parent.fullPath}.${instance.instanceName}`, + hasChildren: Boolean(target) && !recursive && target.instances.length > 0, + warning: instance.unresolved || instance.ambiguous || recursive, + definition: target && target.definition, + definitions: instance.definitions, + site: instance.site, + moduleId: target && !recursive ? target.id : undefined, + seen, + }; +} + +/// The chain of row ids leading to a full path such as `TB.dut.inst1`, or +/// `undefined` when the path no longer exists or no longer names one row. +/// +/// Walked from the roots rather than looked up in a table of every path, +/// because that table is the thing this file stopped building. +function bookmarkChain(model, path) { + if (typeof path !== 'string' || path === '') return undefined; + const [head, ...rest] = path.split('.'); + let found; + for (const { module, fallback } of model.roots) { + if (module.moduleName !== head) continue; + const chain = descend(model, rootNode(model, module, fallback), rest); + if (!chain) continue; + if (found) return undefined; // the path names more than one row + found = chain; + } + return found; +} + +function descend(model, node, names) { + const chain = [node.id]; + let current = node; + for (const name of names) { + const matches = childrenOf(model, current).filter((child) => child.instanceName === name); + if (matches.length !== 1) return undefined; + [current] = matches; + chain.push(current.id); + } + return chain; +} + +function idForPath(model, path) { + const chain = bookmarkChain(model, path); + return chain && chain[chain.length - 1]; +} + +module.exports = { + SEARCH_LIMIT, + bookmarkChain, + buildHierarchy, + childrenOf, + fuzzyScore, + idForPath, + locationKey, + searchHierarchy, + searchTarget, + treeRows, + validateSnapshot, +}; diff --git a/editors/vscode/hierarchyModel_test.js b/editors/vscode/hierarchyModel_test.js new file mode 100644 index 0000000..f20f821 --- /dev/null +++ b/editors/vscode/hierarchyModel_test.js @@ -0,0 +1,409 @@ +const assert = require('assert/strict'); +const { + SEARCH_LIMIT, + bookmarkChain, + buildHierarchy, + childrenOf, + fuzzyScore, + idForPath, + searchHierarchy, + searchTarget, + treeRows, +} = require('./hierarchyModel'); + +// The schema-2 wire the server sends: a file table, four-number ranges, no ids +// and no per-instance `definitions` — the model rebuilds all three. +const FILES = [ + 'file:///tb.sv', + 'file:///top.sv', + 'file:///block.sv', + 'file:///leaf.sv', + 'file:///alpha.sv', +]; + +function site(file, line, start, end) { + return { file, range: [line, 0, line, end + 3], selectionRange: [line, start, line, end] }; +} + +function fixture() { + return { + schemaVersion: 2, + revision: 3, + complete: true, + files: FILES, + modules: [ + { moduleName: 'top', definition: site(1, 0, 7, 10), instances: [ + { instanceName: 'inst1', moduleName: 'block', site: site(1, 1, 8, 13) }, + ] }, + { moduleName: 'leaf', definition: site(3, 0, 7, 11), instances: [] }, + { moduleName: 'TB', definition: site(0, 0, 7, 9), instances: [ + { instanceName: 'dut', moduleName: 'top', site: site(0, 1, 6, 9) }, + ] }, + { moduleName: 'block', definition: site(2, 0, 7, 12), instances: [ + { instanceName: 'inst2', moduleName: 'leaf', site: site(2, 1, 7, 12) }, + ] }, + { moduleName: 'alpha_root', definition: site(4, 0, 7, 17), instances: [] }, + ], + }; +} + +/** The rows a view would show with `open` expanded, by label. */ +function labels(model, open = []) { + return treeRows(model, new Set(open), '').rows.map((row) => row.label); +} + +function rootsAreAlphabeticalAndEverythingStartsCollapsed() { + const model = buildHierarchy(fixture()); + assert.deepEqual( + model.roots.map(({ module }) => module.moduleName), + ['alpha_root', 'TB'], + 'the two modules nothing instantiates, case-insensitively alphabetical', + ); + // Owner, 2026-08-29: no level auto-expands. Opening the view shows the roots + // and nothing under them. + assert.deepEqual(labels(model), ['alpha_root', 'TB']); + const [, tb] = treeRows(model, new Set(), '').rows; + assert.equal(tb.hasChildren, true, 'but the twisty says there is more'); + assert.equal(tb.expanded, false); +} + +function openingOneLevelAtATimeWalksTheDesign() { + const model = buildHierarchy(fixture()); + const open = []; + const openTo = (label) => { + const row = treeRows(model, new Set(open), '').rows + .find((candidate) => candidate.label === label); + assert(row, `${label} is not on screen: ${labels(model, open).join(', ')}`); + open.push(row.id); + return row; + }; + openTo('TB'); + assert.deepEqual(labels(model, open), ['alpha_root', 'TB', 'dut (top)']); + openTo('dut (top)'); + openTo('inst1 (block)'); + assert.deepEqual(labels(model, open), [ + 'alpha_root', 'TB', 'dut (top)', 'inst1 (block)', 'inst2 (leaf)', + ]); + const deep = treeRows(model, new Set(open), '').nodes.get(open[open.length - 1]); + assert.equal(childrenOf(model, deep)[0].fullPath, 'TB.dut.inst1.inst2'); + assert.equal(childrenOf(model, deep)[0].definition.uri, 'file:///leaf.sv'); +} + +function rowIdsSurviveARefresh() { + // What keeps the user's expansion state across a rescan: an id is composed + // from URIs and declaration positions, not from array order. + const first = buildHierarchy(fixture()); + const shuffled = fixture(); + shuffled.modules.reverse(); + shuffled.revision = 4; + const second = buildHierarchy(shuffled); + const open = treeRows(first, new Set(), '').rows.map((row) => row.id); + assert.deepEqual(treeRows(second, new Set(), '').rows.map((row) => row.id), open); + assert.deepEqual(labels(second, open), labels(first, open)); +} + +function bookmarksResolveByPathWithoutATableOfEveryPath() { + const model = buildHierarchy(fixture()); + const chain = bookmarkChain(model, 'TB.dut.inst1.inst2'); + assert.equal(chain.length, 4); + assert.equal(idForPath(model, 'TB.dut.inst1.inst2'), chain[3]); + assert.equal(idForPath(model, 'TB.dut.nope'), undefined); + assert.equal(idForPath(model, ''), undefined); + // Expanding the chain's ancestors is what reveals the row. + const { rows } = treeRows(model, new Set(chain.slice(0, -1)), 'TB.dut.inst1.inst2'); + assert.equal(rows.filter((row) => row.bookmarked).length, 1); + assert.equal(rows.find((row) => row.bookmarked).label, 'inst2 (leaf)'); +} + +function searchScansTheFlatIndexAndKeepsAncestorContext() { + const model = buildHierarchy(fixture()); + const found = searchHierarchy(model, 'is2'); + assert.equal(found.rows.length, 1, 'one row per instance, not one per path'); + assert.equal(found.rows[0].label, 'inst2 (leaf)'); + assert.equal(found.rows[0].detail, 'in block', 'the row says which module writes it'); + assert.equal(searchHierarchy(model, 'tb.sv').total, 0, 'filenames are not searched'); + assert.equal(searchHierarchy(model, 'TB.dut').total, 0, 'full paths are not searched'); + assert.equal(searchHierarchy(model, '').total, 0, 'an empty query is not match-everything'); + + const target = searchTarget(model, found.rows[0].id); + assert.equal(target.kind, 'instance'); + assert.equal(target.site.uri, 'file:///block.sv'); + assert.equal(target.definition.uri, 'file:///leaf.sv'); + assert.equal(target.fullPath, undefined, 'a flat hit has no one path'); + assert.equal(searchTarget(model, 'find:nope'), undefined); + assert.equal(searchTarget(model, 'root:whatever'), undefined); +} + +function recursionAndAmbiguityStayFinite() { + // `A` and `B` instantiate each other — the cycle — and `B` instantiates `C`, + // which two files declare, so every `C` row is ambiguous. Ambiguity is the + // model's own conclusion from the module table: the wire says only that the + // instance's type is spelled `C`. + const model = buildHierarchy({ + schemaVersion: 2, + revision: 1, + complete: true, + files: ['file:///a.sv', 'file:///b.sv', 'file:///c.sv', 'file:///other-c.sv'], + modules: [ + { moduleName: 'A', definition: site(0, 0, 7, 8), instances: [ + { instanceName: 'u_b', moduleName: 'B', site: site(0, 1, 4, 7) }, + ] }, + { moduleName: 'B', definition: site(1, 0, 7, 8), instances: [ + { instanceName: 'u_a', moduleName: 'A', site: site(1, 1, 4, 7) }, + { instanceName: 'u_amb', moduleName: 'C', site: site(1, 2, 4, 9) }, + ] }, + { moduleName: 'C', definition: site(2, 0, 7, 8), instances: [] }, + { moduleName: 'C', definition: site(3, 0, 7, 8), instances: [] }, + ], + }); + assert.deepEqual( + model.roots.map(({ module, fallback }) => [module.moduleName, fallback]), + [['C', false], ['C', false], ['A', true]], + 'the two unparented `C` declarations, then one fallback root for the cycle', + ); + + // Open A, then u_b: the `u_a` under it is the cycle closing, and it is a leaf. + const open = []; + for (const label of ['A', 'u_b (B)']) { + open.push(treeRows(model, new Set(open), '').rows + .find((candidate) => candidate.label === label).id); + } + const { rows } = treeRows(model, new Set(open), ''); + const recursive = rows.find((row) => row.kind === 'instance' && row.detail === 'recursive'); + assert(recursive, 'the repeated edge is present and marked'); + assert.equal(recursive.label, 'u_a (A)'); + assert.equal(recursive.hasChildren, false, 'and does not open again'); + const ambiguous = rows.find((row) => row.detail === 'ambiguous'); + assert(ambiguous, 'a type two files declare is ambiguous'); + assert.equal(ambiguous.hasChildren, false); +} + +function scoringIsDeterministic() { + assert(fuzzyScore('inst2', 'inst2') > fuzzyScore('inst20', 'inst2')); + assert(fuzzyScore('u_fifo', 'ufi') > fuzzyScore('unrelated_f_i', 'ufi')); + assert.equal(fuzzyScore('module', 'xyz'), -1); +} + +function malformedSnapshotsAreRejected() { + assert.throws(() => buildHierarchy({ schemaVersion: 1, files: [], modules: [] }), /unsupported/); + assert.throws(() => buildHierarchy({ ...fixture(), files: undefined }), /unsupported/); + const noRange = fixture(); + noRange.modules[0].definition.selectionRange = null; + assert.throws(() => buildHierarchy(noRange), /malformed/); + const shortRange = fixture(); + shortRange.modules[0].instances[0].site.range = [1, 2, 3]; + assert.throws(() => buildHierarchy(shortRange), /malformed/); + const offTable = fixture(); + offTable.modules[0].definition.file = FILES.length; + assert.throws(() => buildHierarchy(offTable), /malformed/); +} + +/** The wire is narrow; the model is not. Everything the rest of the extension + * reads — a URI, `{ line, character }` positions, an id, the declarations an + * instance's module name resolves to — is rebuilt here. */ +function theNarrowWireIsRebuiltIntoTheWideModel() { + const model = buildHierarchy(fixture()); + const block = model.modules.find((module) => module.moduleName === 'block'); + const [inst2] = block.instances; + assert.equal(inst2.site.uri, 'file:///block.sv'); + assert.deepEqual(inst2.site.selectionRange, { + start: { line: 1, character: 7 }, + end: { line: 1, character: 12 }, + }); + assert.equal(inst2.id, 'file:///block.sv#1:7'); + assert.equal(inst2.definitions.length, 1, 'rebuilt from the module table'); + assert.equal(inst2.definitions[0].uri, 'file:///leaf.sv'); + assert.equal(inst2.unresolved, false); + assert.equal(inst2.ambiguous, false); +} + +/** The owner's freeze, turned into a budget. 20 000 modules and 100 000 + * instances — six times opentitan — built once, then queried. What is asserted + * is the shape of the cost with room to spare on a slow machine: an array scan + * is microseconds per entry, so 120 000 entries is single-digit milliseconds + * per query. */ +function searchOverAHugeHierarchyStaysInsideItsBudget() { + const MODULES = 20000; + const PER_MODULE = 5; + const files = []; + const modules = []; + for (let m = 0; m < MODULES; m += 1) { + files.push(`file:///gen/mod_${m}.sv`); + const instances = []; + for (let i = 0; i < PER_MODULE; i += 1) { + instances.push({ + instanceName: `u_inst_${m}_${i}`, + moduleName: `mod_${(m + i + 1) % MODULES}`, + site: { file: m, range: [i + 1, 2, i + 1, 40], selectionRange: [i + 1, 6, i + 1, 20] }, + }); + } + modules.push({ + moduleName: `mod_${m}`, + definition: { file: m, range: [0, 0, 9, 9], selectionRange: [0, 7, 0, 14] }, + instances, + }); + } + const snapshot = { schemaVersion: 2, revision: 1, complete: true, files, modules }; + + const builtAt = process.hrtime.bigint(); + const model = buildHierarchy(snapshot); + const buildMs = Number(process.hrtime.bigint() - builtAt) / 1e6; + assert.equal(model.entries.length, MODULES * (PER_MODULE + 1)); + assert(buildMs < 8000, `building the model took ${buildMs.toFixed(1)} ms`); + + // Rows are only built for what is open, so a collapsed tree over 100 000 + // instances is one row per root and nothing else. + const rowsAt = process.hrtime.bigint(); + const { rows } = treeRows(model, new Set(), ''); + const rowsMs = Number(process.hrtime.bigint() - rowsAt) / 1e6; + assert(rows.length <= MODULES, 'a collapsed tree is at most one row per root'); + assert(rowsMs < 500, `the collapsed tree took ${rowsMs.toFixed(1)} ms`); + + // Every prefix of a word typed one character at a time — the keystroke + // sequence that froze the view. + let worst = 0; + for (const query of ['u', 'u_', 'u_i', 'u_in', 'u_ins', 'u_inst', 'u_inst_1', 'mod_999', 'zzz']) { + const at = process.hrtime.bigint(); + const found = searchHierarchy(model, query); + const ms = Number(process.hrtime.bigint() - at) / 1e6; + worst = Math.max(worst, ms); + assert(found.rows.length <= SEARCH_LIMIT, `${query} rendered ${found.rows.length} rows`); + if (found.total > SEARCH_LIMIT) { + assert.equal(found.truncated, found.total - SEARCH_LIMIT, 'the "N more" count'); + } + } + // Single-digit milliseconds is the target; 60 ms is the assertion, so a busy + // machine does not fail a test that is about orders of magnitude. + assert( + worst < 60, + `the slowest query took ${worst.toFixed(1)} ms over ${model.entries.length} entries`, + ); + if (process.env.LUCISV_SEARCH_TIMINGS) { + console.log(` build ${buildMs.toFixed(1)} ms, collapsed tree ${rowsMs.toFixed(2)} ms, worst query ${worst.toFixed(2)} ms`); + } +} + +/** QA (2026-08-29): the counting cutoff must choose the same top rows a full + * sort of every score would — checked here by hand, not by re-deriving + * `truncated` from the same numbers the search already produced. Five + * instances of one module, `leaf`, are scored against `fifo` by the + * documented rule (exact/prefix/substring tiers, then the subsequence loop's + * bonuses), and the ranking below is arithmetic anyone can redo: + * "fifo" exact 10000 + 1 (instance tie) = 10001 + * "fifo_ctrl" prefix, 8000 - (9-4) = 7996 + * "ffifo" substring at 1, 6000-10-(5-4) +1 = 5990 + * "u_fifo" substring at 2, 6000-20-(6-4) +1 = 5979 + * "f_i_f_o" subsequence only +1 = 65 + * "unrelated" no match at all -1 + * so the top 3 are "fifo", "fifo_ctrl", "ffifo" in that order, and 2 more + * (of the 5 real matches) are owed. */ +function topKSearchMatchesWhatAFullSortWouldChoose() { + const files = ['file:///top.sv', 'file:///leaf.sv']; + const names = ['fifo', 'fifo_ctrl', 'ffifo', 'u_fifo', 'f_i_f_o', 'unrelated']; + const instances = names.map((name, i) => ({ + instanceName: name, + moduleName: 'leaf', + site: site(0, i + 1, 2, 6 + name.length), + })); + const snapshot = { + schemaVersion: 2, + revision: 1, + complete: true, + files, + modules: [ + { moduleName: 'top', definition: site(0, 0, 7, 10), instances }, + { moduleName: 'leaf', definition: site(1, 0, 7, 11), instances: [] }, + ], + }; + const model = buildHierarchy(snapshot); + + const found = searchHierarchy(model, 'fifo', 3); + assert.deepEqual( + found.rows.map((row) => row.label.split(' ')[0]), + ['fifo', 'fifo_ctrl', 'ffifo'], + 'the counting cutoff must agree with a full sort by hand', + ); + assert.equal(found.total, 5, 'exactly the five names that contain f, i, f, o in order'); + assert.equal(found.truncated, 2, 'five real matches minus the three shown'); + + // The same query with no cap at all must return every match, in the same + // relative order, as a cross-check that capping never reorders anything. + const uncapped = searchHierarchy(model, 'fifo', 100); + assert.deepEqual( + uncapped.rows.map((row) => row.label.split(' ')[0]), + ['fifo', 'fifo_ctrl', 'ffifo', 'u_fifo', 'f_i_f_o'], + ); +} + +/** QA (2026-08-29): the letter/digit bitmask is a coarse presence test — every + * non-alphanumeric, non-`_` character shares one bit — so it must only ever + * be more permissive than the real scorer, never less. Checked against an + * independent, un-bitmasked subsequence check (`isSubsequence` below, which + * does not use `maskOf` at all) over escaped-identifier-shaped names: an + * instance name a real design can actually carry, with `$`, `.` and `[]` in + * it, none of which are letters or digits and so all fold onto one bit. */ +function theBitmaskPrefilterNeverExcludesATrueSubsequenceMatch() { + function isSubsequence(haystack, needle) { + let cursor = 0; + for (const ch of needle) { + cursor = haystack.indexOf(ch, cursor); + if (cursor < 0) return false; + cursor += 1; + } + return true; + } + + const cases = [ + ['\\pll.ref_clk[0]', 'pll.ref'], + ['\\pll.ref_clk[0]', 'p.r[0'], + ['a$b.c]d', 'a$c]d'], + ['a$b.c]d', 'a.d'], + ['zz9', 'z9'], + ['a0z', 'a0z'], + ]; + for (const [haystack, needle] of cases) { + assert( + isSubsequence(haystack, needle), + `premise: "${needle}" is really a subsequence of "${haystack}"`, + ); + assert( + fuzzyScore(haystack, needle) >= 0, + `the bitmask prefilter excluded a true match: "${needle}" in "${haystack}"`, + ); + } + + // End to end: the same names, reachable through `searchHierarchy`, not just + // through the scorer it calls. + const files = ['file:///top.sv', 'file:///leaf.sv']; + const model = buildHierarchy({ + schemaVersion: 2, + revision: 1, + complete: true, + files, + modules: [ + { moduleName: 'top', definition: site(0, 0, 7, 10), instances: [ + { instanceName: '\\pll.ref_clk[0]', moduleName: 'leaf', site: site(0, 1, 2, 20) }, + ] }, + { moduleName: 'leaf', definition: site(1, 0, 7, 11), instances: [] }, + ], + }); + assert.equal(searchHierarchy(model, 'pll.ref').rows.length, 1); + assert.equal(searchHierarchy(model, 'p.r[0').rows.length, 1); +} + +for (const test of [ + rootsAreAlphabeticalAndEverythingStartsCollapsed, + openingOneLevelAtATimeWalksTheDesign, + rowIdsSurviveARefresh, + bookmarksResolveByPathWithoutATableOfEveryPath, + searchScansTheFlatIndexAndKeepsAncestorContext, + recursionAndAmbiguityStayFinite, + scoringIsDeterministic, + malformedSnapshotsAreRejected, + theNarrowWireIsRebuiltIntoTheWideModel, + searchOverAHugeHierarchyStaysInsideItsBudget, + topKSearchMatchesWhatAFullSortWouldChoose, + theBitmaskPrefilterNeverExcludesATrueSubsequenceMatch, +]) test(); + +console.log('hierarchy model: OK — collapsed roots, lazy levels, stable ids, bookmarks, search, cycles, validation, wire rebuilding, and the 120k-entry search budget'); diff --git a/editors/vscode/hierarchyView.js b/editors/vscode/hierarchyView.js new file mode 100644 index 0000000..37b9852 --- /dev/null +++ b/editors/vscode/hierarchyView.js @@ -0,0 +1,276 @@ +const crypto = require('crypto'); +const vscode = require('vscode'); +const { + bookmarkChain, + buildHierarchy, + idForPath, + searchHierarchy, + searchTarget, + treeRows, +} = require('./hierarchyModel'); + +const VIEW_ID = 'lucisv.hierarchy'; +const SNAPSHOT_METHOD = 'lucisv/moduleHierarchy'; +const CHANGED_METHOD = 'lucisv/moduleHierarchyChanged'; +const BOOKMARK_KEY = 'lucisv.hierarchy.bookmark'; +const REFRESH_DEBOUNCE_MS = 100; + +class HierarchyView { + constructor(context, client) { + this.context = context; + this.client = client; + this.view = undefined; + this.model = undefined; + this.query = ''; + // Which rows the user has opened. Row ids are composed from URIs and + // declaration positions, so they survive a refresh and what was open stays + // open — nothing is expanded on the user's behalf (owner, 2026-08-29). + this.expanded = new Set(); + this.nodes = new Map(); + this.request = 0; + this.refreshTimer = undefined; + this.bookmarkPath = context.workspaceState.get(BOOKMARK_KEY, ''); + this.lostBookmarkReported = false; + + context.subscriptions.push( + vscode.window.registerWebviewViewProvider(VIEW_ID, this, { + webviewOptions: { retainContextWhenHidden: true }, + }), + vscode.commands.registerCommand('lucisv.hierarchy.refresh', () => this.refresh()), + vscode.commands.registerCommand('lucisv.hierarchy.clearBookmark', () => this.setBookmark('')), + client.onNotification(CHANGED_METHOD, () => this.scheduleRefresh()), + { dispose: () => clearTimeout(this.refreshTimer) }, + ); + } + + resolveWebviewView(view) { + this.view = view; + const media = vscode.Uri.joinPath(this.context.extensionUri, 'media'); + view.webview.options = { + enableScripts: true, + localResourceRoots: [media], + }; + this.context.subscriptions.push( + view.webview.onDidReceiveMessage((message) => this.message(message)), + view.onDidDispose(() => { + if (this.view === view) this.view = undefined; + }), + ); + // Install the receiver before loading the document: its script posts + // `ready` immediately, and even a fast webview must not outrun the host. + view.webview.html = html(view.webview, media); + } + + onStarted() { + this.refresh(); + } + + scheduleRefresh() { + clearTimeout(this.refreshTimer); + this.refreshTimer = setTimeout(() => this.refresh(), REFRESH_DEBOUNCE_MS); + } + + async refresh() { + if (!this.view) return; + const asked = ++this.request; + this.post({ type: 'status', text: 'Loading hierarchy…' }); + try { + const snapshot = await this.client.sendRequest(SNAPSHOT_METHOD, {}); + if (asked !== this.request) return; + this.model = buildHierarchy(snapshot); + if (this.bookmarkPath && !idForPath(this.model, this.bookmarkPath)) { + await this.context.workspaceState.update(BOOKMARK_KEY, undefined); + this.bookmarkPath = ''; + if (!this.lostBookmarkReported) { + this.lostBookmarkReported = true; + vscode.window.showWarningMessage('The bookmarked lucisv instance no longer exists uniquely.'); + } + } else { + this.lostBookmarkReported = false; + } + this.render(); + } catch (error) { + if (asked !== this.request) return; + const code = error && (error.code || (error.data && error.data.code)); + const oldServer = code === -32601 || /method.*not found/i.test(String(error && error.message)); + this.post({ + type: 'status', + error: true, + text: oldServer + ? 'This lucisv server is too old for the hierarchy sidebar.' + : 'The hierarchy is unavailable while the language server is restarting.', + }); + } + } + + /// Post exactly the rows the view shows — the open part of the tree, or one + /// page of search results. Never the whole design: shipping every path of it + /// on every keystroke is what froze the UI. + render() { + if (!this.model) return; + const common = { + type: 'render', + revision: this.model.revision, + complete: this.model.complete, + query: this.query, + empty: this.model.roots.length === 0, + }; + if (this.query.trim() !== '') { + const found = searchHierarchy(this.model, this.query); + this.post({ ...common, mode: 'search', rows: found.rows, truncated: found.truncated, total: found.total }); + return; + } + const tree = treeRows(this.model, this.expanded, this.bookmarkPath); + this.nodes = tree.nodes; + this.post({ ...common, mode: 'tree', rows: tree.rows, truncated: 0, total: tree.rows.length }); + } + + async message(message) { + if (!message || typeof message.type !== 'string') return; + if (message.type === 'ready') { + await this.refresh(); + return; + } + if (message.type === 'search' && typeof message.query === 'string') { + this.query = message.query.slice(0, 256); + this.render(); + return; + } + if (!this.model || typeof message.id !== 'string') return; + if (message.type === 'toggle') { + if (this.expanded.has(message.id)) this.expanded.delete(message.id); + else this.expanded.add(message.id); + this.render(); + return; + } + // A tree row is a path the view is currently showing; a search row names a + // module and, for an instance, which module writes it. Both resolve to the + // same three things an action needs: a site, a definition, and candidates. + const node = this.nodes.get(message.id) || searchTarget(this.model, message.id); + if (!node) return; + if (message.type === 'activate') { + await this.show(node.kind === 'instance' ? node.site : node.definition, false); + return; + } + if (message.type !== 'context' || typeof message.action !== 'string') return; + const actions = new Set(['copyPath', 'definition', 'instance', 'bookmark', 'openRight']); + if (!actions.has(message.action) || node.kind !== 'instance') return; + // A search hit is one row for an instance however many paths reach it, so + // it has no one full path to copy or bookmark. + if (!node.fullPath && (message.action === 'copyPath' || message.action === 'bookmark')) { + vscode.window.showWarningMessage('Clear the search to copy or bookmark an instance path.'); + return; + } + switch (message.action) { + case 'copyPath': + await vscode.env.clipboard.writeText(node.fullPath); + break; + case 'definition': + await this.showDefinition(node, false); + break; + case 'instance': + await this.show(node.site, false); + break; + case 'bookmark': + await this.setBookmark(this.bookmarkPath === node.fullPath ? '' : node.fullPath); + break; + case 'openRight': + await this.showDefinition(node, true); + break; + default: + break; + } + } + + async setBookmark(path) { + this.bookmarkPath = path; + await this.context.workspaceState.update(BOOKMARK_KEY, path || undefined); + // The one expansion the view performs for the user, and only because the + // user asked for it by bookmarking: the direct ancestors of the marked row. + const chain = path && bookmarkChain(this.model, path); + if (chain) for (const id of chain.slice(0, -1)) this.expanded.add(id); + this.render(); + } + + async showDefinition(node, beside) { + let location; + if (node.definitions.length === 0) { + vscode.window.showWarningMessage(`No indexed definition was found for module ${node.moduleName}.`); + return; + } + if (node.definitions.length === 1) { + [location] = node.definitions; + } else { + const choices = node.definitions.map((candidate) => ({ + label: vscode.workspace.asRelativePath(vscode.Uri.parse(candidate.uri), false), + description: `${candidate.selectionRange.start.line + 1}:${candidate.selectionRange.start.character + 1}`, + location: candidate, + })); + const picked = await vscode.window.showQuickPick(choices, { + placeHolder: `Choose a definition for ${node.moduleName}`, + }); + if (!picked) return; + location = picked.location; + } + await this.show(location, beside); + } + + async show(location, beside) { + if (!location) return; + const document = await vscode.workspace.openTextDocument(vscode.Uri.parse(location.uri)); + await vscode.window.showTextDocument(document, { + viewColumn: beside ? vscode.ViewColumn.Beside : vscode.ViewColumn.Active, + preserveFocus: false, + preview: !beside, + selection: asRange(location.selectionRange), + }); + } + + post(message) { + if (this.view) this.view.webview.postMessage(message); + } +} + +function asRange(range) { + return new vscode.Range( + range.start.line, + range.start.character, + range.end.line, + range.end.character, + ); +} + +function html(webview, media) { + const nonce = crypto.randomBytes(16).toString('base64'); + const script = webview.asWebviewUri(vscode.Uri.joinPath(media, 'hierarchy.js')); + const style = webview.asWebviewUri(vscode.Uri.joinPath(media, 'hierarchy.css')); + return ` + + + + + + + lucisv Hierarchy + + +
+ +
+
Loading hierarchy…
+
+ + + + + +`; +} + +module.exports = { HierarchyView, VIEW_ID }; diff --git a/editors/vscode/hierarchyView_test.js b/editors/vscode/hierarchyView_test.js new file mode 100644 index 0000000..06f8197 --- /dev/null +++ b/editors/vscode/hierarchyView_test.js @@ -0,0 +1,190 @@ +const assert = require('assert/strict'); +const Module = require('module'); + +const disposables = () => ({ dispose() {} }); +const posted = []; +const copied = []; +const opened = []; +const shown = []; +const warned = []; +let requests = 0; +let provider; +let receive; +let changed; + +class Range { + constructor(startLine, startCharacter, endLine, endCharacter) { + this.start = { line: startLine, character: startCharacter }; + this.end = { line: endLine, character: endCharacter }; + } +} + +const vscode = { + Uri: { + parse(value) { return { value, fsPath: value.replace('file://', ''), toString: () => value }; }, + joinPath(base, ...parts) { + const value = [base.value || base.toString(), ...parts].join('/'); + return { value, toString: () => value }; + }, + }, + Range, + ViewColumn: { Active: 1, Beside: 2 }, + env: { clipboard: { async writeText(value) { copied.push(value); } } }, + commands: { registerCommand() { return disposables(); } }, + workspace: { + asRelativePath(uri) { return uri.fsPath; }, + async openTextDocument(uri) { + opened.push(uri.value); + return { + uri, + lineCount: 6, + lineAt(line) { return { text: `line ${line + 1}` }; }, + }; + }, + }, + window: { + registerWebviewViewProvider(_id, value) { provider = value; return disposables(); }, + async showTextDocument(document, options) { shown.push({ document, options }); }, + async showQuickPick(items) { return items[0]; }, + showWarningMessage(text) { warned.push(text); }, + }, +}; + +const originalLoad = Module._load; +Module._load = function load(request, parent, main) { + if (request === 'vscode') return vscode; + return originalLoad(request, parent, main); +}; +const { HierarchyView } = require('./hierarchyView'); +Module._load = originalLoad; + +// The schema-2 wire: a file table and four-number ranges, no ids and no +// per-instance `definitions` — `hierarchyModel.js` rebuilds all three. +function place(file, line, start, end) { + return { file, range: [line, 0, line, end + 2], selectionRange: [line, start, line, end] }; +} + +const snapshot = { + schemaVersion: 2, + revision: 1, + complete: true, + files: ['file:///top.sv', 'file:///sub.sv'], + modules: [ + { moduleName: 'top', definition: place(0, 0, 7, 10), instances: [ + { instanceName: 'u', moduleName: 'sub', site: place(0, 1, 6, 9) }, + ] }, + { moduleName: 'sub', definition: place(1, 0, 7, 10), instances: [] }, + ], +}; + +const state = new Map(); +const context = { + extensionUri: { value: 'file:///extension', toString: () => 'file:///extension' }, + subscriptions: [], + workspaceState: { + get(key, fallback) { return state.has(key) ? state.get(key) : fallback; }, + async update(key, value) { if (value === undefined) state.delete(key); else state.set(key, value); }, + }, +}; +const client = { + async sendRequest(method) { + assert.equal(method, 'lucisv/moduleHierarchy'); + requests += 1; + return snapshot; + }, + onNotification(method, handler) { + assert.equal(method, 'lucisv/moduleHierarchyChanged'); + changed = handler; + return disposables(); + }, +}; + +new HierarchyView(context, client); +assert(provider, 'the webview provider is registered'); +const webview = { + cspSource: 'vscode-webview:', + options: undefined, + html: '', + asWebviewUri(uri) { return uri.toString(); }, + postMessage(message) { posted.push(message); }, + onDidReceiveMessage(handler) { receive = handler; return disposables(); }, +}; +provider.resolveWebviewView({ + webview, + onDidDispose() { return disposables(); }, +}); +assert(webview.html.includes('Search module or instance')); +assert(webview.html.includes('Content-Security-Policy')); + +async function run() { + await receive({ type: 'ready' }); + const rendered = () => posted.findLast((message) => message.type === 'render'); + assert(rendered(), 'ready requests and renders a snapshot'); + + // Owner, 2026-08-29: everything starts collapsed — one row, the root. + assert.equal(rendered().mode, 'tree'); + assert.deepEqual(rendered().rows.map((row) => row.label), ['top']); + const root = rendered().rows[0]; + assert.equal(root.hasChildren, true); + assert.equal(root.expanded, false); + + // Opening is the user's own act, and it is the only thing that builds the + // level below. + await receive({ type: 'toggle', id: root.id }); + assert.deepEqual(rendered().rows.map((row) => row.label), ['top', 'u (sub)']); + const instance = rendered().rows[1]; + + // A query swaps in a flat, capped result list; clearing it puts the tree + // back with the same row open and no new snapshot request. + const requestsBefore = requests; + await receive({ type: 'search', query: 'u' }); + assert.equal(rendered().mode, 'search'); + assert(rendered().rows.some((row) => row.label === 'u (sub)')); + assert.equal(rendered().truncated, 0); + await receive({ type: 'search', query: '' }); + assert.equal(rendered().mode, 'tree'); + assert.deepEqual(rendered().rows.map((row) => row.label), ['top', 'u (sub)']); + assert.equal(requests, requestsBefore, 'searching never asks the server again'); + + await receive({ type: 'context', action: 'copyPath', id: instance.id }); + assert.deepEqual(copied, ['top.u']); + await receive({ type: 'context', action: 'instance', id: instance.id }); + assert.equal(opened.at(-1), 'file:///top.sv'); + assert.equal(shown.at(-1).options.viewColumn, 1); + await receive({ type: 'context', action: 'openRight', id: instance.id }); + assert.equal(opened.at(-1), 'file:///sub.sv'); + assert.equal(shown.at(-1).options.viewColumn, 2); + assert.equal(shown.at(-1).options.preview, false); + + await receive({ type: 'context', action: 'bookmark', id: instance.id }); + assert.equal(state.get('lucisv.hierarchy.bookmark'), 'top.u'); + assert.equal(rendered().rows.find((row) => row.bookmarked).label, 'u (sub)'); + + // A search row navigates, but has no one path to copy or bookmark. + await receive({ type: 'search', query: 'u' }); + const hit = rendered().rows.find((row) => row.kind === 'instance'); + await receive({ type: 'context', action: 'definition', id: hit.id }); + assert.equal(opened.at(-1), 'file:///sub.sv'); + const copiedBefore = copied.length; + await receive({ type: 'context', action: 'copyPath', id: hit.id }); + assert.equal(copied.length, copiedBefore, 'a flat hit has no full path to copy'); + assert.equal(warned.at(-1), 'Clear the search to copy or bookmark an instance path.'); + await receive({ type: 'search', query: '' }); + + // The source-line hover preview was removed at the owner's request + // (2026-08-29): a `hover` message is now one the view does not answer, and + // it must not resurrect the code that read a document behind the tree. + const before = posted.length; + await receive({ type: 'hover', id: instance.id }); + assert.equal(posted.length, before, 'a hover posts nothing back'); + assert(!posted.some((message) => message.type === 'preview'), 'no preview is ever posted'); + assert(!webview.html.includes('id="preview"'), 'and the popover is gone from the markup'); + + assert.equal(typeof changed, 'function'); + console.log('hierarchy view: OK — collapsed rows, lazy opening, search list, navigation, menu, bookmark, and no preview'); +} + +run().catch((error) => { + console.error(error); + process.exitCode = 1; +}); diff --git a/editors/vscode/images/hierarchy.svg b/editors/vscode/images/hierarchy.svg new file mode 100644 index 0000000..13447e2 --- /dev/null +++ b/editors/vscode/images/hierarchy.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/editors/vscode/media/hierarchy.css b/editors/vscode/media/hierarchy.css new file mode 100644 index 0000000..7ae082c --- /dev/null +++ b/editors/vscode/media/hierarchy.css @@ -0,0 +1,85 @@ +:root { color-scheme: light dark; } +* { box-sizing: border-box; } +body { + margin: 0; + padding: 0; + color: var(--vscode-foreground); + background: var(--vscode-sideBar-background); + font: var(--vscode-font-weight) var(--vscode-font-size)/1.4 var(--vscode-font-family); + overflow: hidden auto; +} +.search-wrap { + position: sticky; + top: 0; + z-index: 3; + padding: 6px 8px; + background: var(--vscode-sideBar-background); +} +#search { + width: 100%; + height: 26px; + padding: 2px 7px; + color: var(--vscode-input-foreground); + background: var(--vscode-input-background); + border: 1px solid var(--vscode-input-border, transparent); + outline: none; +} +#search:focus { border-color: var(--vscode-focusBorder); } +#status { padding: 8px 10px; color: var(--vscode-descriptionForeground); } +#status.error { color: var(--vscode-errorForeground); } +#tree, #results { padding-bottom: 8px; } +#more { padding: 4px 10px 10px; color: var(--vscode-descriptionForeground); } +.row { + --indent: calc(var(--depth) * 12px); + width: 100%; + min-height: 22px; + display: flex; + align-items: center; + gap: 4px; + padding: 1px 8px 1px calc(4px + var(--indent)); + border: 1px solid transparent; + color: inherit; + background: transparent; + font: inherit; + text-align: left; + cursor: default; +} +.row:hover { background: var(--vscode-list-hoverBackground); } +.row:focus { outline: 1px solid var(--vscode-list-focusOutline, var(--vscode-focusBorder)); outline-offset: -1px; } +.row.match .label { font-weight: 600; } +.row.bookmarked { + background: color-mix(in srgb, var(--vscode-charts-yellow, #cca700) 35%, transparent); + border-color: var(--vscode-charts-yellow, #cca700); +} +.row.warning .detail { color: var(--vscode-list-warningForeground, var(--vscode-editorWarning-foreground)); } +.twisty { width: 12px; flex: 0 0 12px; text-align: center; } +.icon { width: 14px; flex: 0 0 14px; color: var(--vscode-symbolIcon-moduleForeground, var(--vscode-foreground)); } +.label { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.detail { margin-left: auto; font-size: .9em; color: var(--vscode-descriptionForeground); } +#menu { + position: fixed; + z-index: 10; + width: 185px; + padding: 4px; + background: var(--vscode-menu-background); + color: var(--vscode-menu-foreground); + border: 1px solid var(--vscode-menu-border, var(--vscode-widget-border)); + box-shadow: 0 4px 12px var(--vscode-widget-shadow); +} +#menu button { + display: block; + width: 100%; + padding: 4px 8px; + border: 0; + color: inherit; + background: transparent; + text-align: left; + font: inherit; +} +#menu button:hover, #menu button:focus { + color: var(--vscode-menu-selectionForeground); + background: var(--vscode-menu-selectionBackground); + outline: none; +} +[hidden] { display: none !important; } +@media (forced-colors: active) { .row.bookmarked { outline: 2px solid Highlight; } } diff --git a/editors/vscode/media/hierarchy.js b/editors/vscode/media/hierarchy.js new file mode 100644 index 0000000..4503e65 --- /dev/null +++ b/editors/vscode/media/hierarchy.js @@ -0,0 +1,192 @@ +// The hierarchy view's renderer. It draws exactly the rows the extension host +// sends and owns no model of its own: the host holds the flat snapshot, opens +// one level at a time, and answers a query from a prebuilt index. What used to +// arrive here was every path of the whole design, rebuilt and re-sent on every +// keystroke — the freeze the owner reported on 2026-08-29. + +const vscode = acquireVsCodeApi(); +const search = document.getElementById('search'); +const tree = document.getElementById('tree'); +const results = document.getElementById('results'); +const more = document.getElementById('more'); +const status = document.getElementById('status'); +const menu = document.getElementById('menu'); + +/** Long enough that a fast typist sends one query, short enough to feel live. */ +const SEARCH_DEBOUNCE_MS = 60; + +let payload = { mode: 'tree', rows: [], truncated: 0, query: '' }; +let menuNode; +let searchTimer; + +search.addEventListener('input', () => { + clearTimeout(searchTimer); + searchTimer = setTimeout( + () => vscode.postMessage({ type: 'search', query: search.value }), + SEARCH_DEBOUNCE_MS, + ); +}); +search.addEventListener('keydown', (event) => { + if (event.key === 'Escape' && search.value) { + search.value = ''; + clearTimeout(searchTimer); + vscode.postMessage({ type: 'search', query: '' }); + } + if (event.key === 'ArrowDown') firstVisibleRow()?.focus(); +}); + +window.addEventListener('message', ({ data }) => { + if (!data || typeof data.type !== 'string') return; + if (data.type === 'status') { + status.textContent = data.text; + status.classList.toggle('error', Boolean(data.error)); + status.hidden = false; + if (data.error) { + tree.replaceChildren(); + results.replaceChildren(); + } + return; + } + if (data.type !== 'render') return; + payload = data; + if (search.value !== data.query) search.value = data.query; + render(); +}); + +// The tree and the result list are two containers, and a query swaps which one +// is shown. Searching therefore never tears the tree down, and clearing the +// search puts back exactly the rows that were open — no re-request, no rebuild. +function render() { + const searching = payload.mode === 'search'; + const container = searching ? results : tree; + const fragment = document.createDocumentFragment(); + for (const row of payload.rows) fragment.appendChild(renderRow(row, searching)); + container.replaceChildren(fragment); + tree.hidden = searching; + results.hidden = !searching; + + more.textContent = payload.truncated > 0 + ? `${payload.truncated} more match${payload.truncated === 1 ? '' : 'es'} — narrow the search.` + : ''; + more.hidden = payload.truncated === 0; + + const message = payload.empty + ? 'No indexed modules.' + : (searching && payload.rows.length === 0 + ? 'No module or instance name matches.' + : (!payload.complete ? 'Indexing… showing a partial hierarchy.' : '')); + status.textContent = message; + status.hidden = message === ''; + status.classList.remove('error'); +} + +function renderRow(row, searching) { + const wrapper = document.createElement('div'); + wrapper.className = 'node'; + wrapper.dataset.id = row.id; + const button = document.createElement('button'); + button.className = 'row'; + button.type = 'button'; + button.setAttribute('role', searching ? 'option' : 'treeitem'); + button.setAttribute('aria-level', String(row.depth + 1)); + button.style.setProperty('--depth', row.depth); + if (row.bookmarked) button.classList.add('bookmarked'); + if (row.warning) button.classList.add('warning'); + if (searching) button.classList.add('match'); + if (row.hasChildren) button.setAttribute('aria-expanded', String(row.expanded)); + + const twisty = document.createElement('span'); + twisty.className = 'twisty'; + twisty.textContent = row.hasChildren ? (row.expanded ? '⌄' : '›') : ''; + twisty.setAttribute('aria-hidden', 'true'); + const icon = document.createElement('span'); + icon.className = 'icon'; + icon.textContent = row.kind === 'module' ? '▣' : (row.detail === 'recursive' ? '↻' : '◇'); + icon.setAttribute('aria-hidden', 'true'); + const label = document.createElement('span'); + label.className = 'label'; + label.textContent = row.label; + const detail = document.createElement('span'); + detail.className = 'detail'; + detail.textContent = row.detail || ''; + button.append(twisty, icon, label, detail); + + button.addEventListener('click', (event) => { + if (row.hasChildren && event.detail === 1 && event.offsetX < 28 + row.depth * 12) { + vscode.postMessage({ type: 'toggle', id: row.id }); + } else { + vscode.postMessage({ type: 'activate', id: row.id }); + } + }); + button.addEventListener('dblclick', () => { + if (row.hasChildren) vscode.postMessage({ type: 'toggle', id: row.id }); + }); + button.addEventListener('contextmenu', (event) => openMenu(event, row)); + button.addEventListener('keydown', (event) => key(event, row)); + wrapper.appendChild(button); + return wrapper; +} + +function key(event, row) { + if ((event.key === 'ContextMenu') || (event.shiftKey && event.key === 'F10')) { + event.preventDefault(); + const rect = event.currentTarget.getBoundingClientRect(); + openMenu({ preventDefault() {}, clientX: rect.left + 16, clientY: rect.bottom }, row); + return; + } + if (event.key === 'Enter' || event.key === ' ') { + event.preventDefault(); + vscode.postMessage({ type: 'activate', id: row.id }); + } else if (event.key === 'ArrowRight' && row.hasChildren) { + event.preventDefault(); + if (!row.expanded) vscode.postMessage({ type: 'toggle', id: row.id }); + else nextRow(event.currentTarget)?.focus(); + } else if (event.key === 'ArrowLeft') { + event.preventDefault(); + if (row.hasChildren && row.expanded) vscode.postMessage({ type: 'toggle', id: row.id }); + else previousRow(event.currentTarget)?.focus(); + } else if (event.key === 'ArrowDown') { + event.preventDefault(); + nextRow(event.currentTarget)?.focus(); + } else if (event.key === 'ArrowUp') { + event.preventDefault(); + previousRow(event.currentTarget)?.focus(); + } +} + +function shown() { return payload.mode === 'search' ? results : tree; } +function rows() { return [...shown().querySelectorAll('.row')]; } +function firstVisibleRow() { return rows()[0]; } +function nextRow(row) { const all = rows(); return all[all.indexOf(row) + 1]; } +function previousRow(row) { const all = rows(); return all[all.indexOf(row) - 1]; } + +function openMenu(event, row) { + event.preventDefault(); + if (row.kind !== 'instance') return; + menuNode = row; + menu.hidden = false; + menu.style.left = `${Math.min(event.clientX, innerWidth - 190)}px`; + menu.style.top = `${Math.min(event.clientY, innerHeight - 180)}px`; + menu.querySelector('[data-action="bookmark"]').textContent = row.bookmarked + ? 'Remove Highlight / Bookmark' : 'Highlight / Bookmark'; + menu.querySelector('button').focus(); +} + +menu.addEventListener('click', (event) => { + const action = event.target && event.target.dataset.action; + if (action && menuNode) vscode.postMessage({ type: 'context', action, id: menuNode.id }); + closeMenu(); +}); +menu.addEventListener('keydown', (event) => { + const items = [...menu.querySelectorAll('button')]; + const at = items.indexOf(document.activeElement); + if (event.key === 'Escape') closeMenu(); + if (event.key === 'ArrowDown') items[(at + 1) % items.length].focus(); + if (event.key === 'ArrowUp') items[(at - 1 + items.length) % items.length].focus(); +}); +document.addEventListener('mousedown', (event) => { + if (!menu.contains(event.target)) closeMenu(); +}); +function closeMenu() { menu.hidden = true; menuNode = undefined; } + +vscode.postMessage({ type: 'ready' }); diff --git a/editors/vscode/package.json b/editors/vscode/package.json index dd38dd8..c1e2820 100644 --- a/editors/vscode/package.json +++ b/editors/vscode/package.json @@ -50,9 +50,54 @@ "main": "./extension.js", "activationEvents": [ "onLanguage:verilog", - "onLanguage:systemverilog" + "onLanguage:systemverilog", + "onView:lucisv.hierarchy" ], "contributes": { + "viewsContainers": { + "activitybar": [ + { + "id": "lucisv", + "title": "lucisv", + "icon": "images/hierarchy.svg" + } + ] + }, + "views": { + "lucisv": [ + { + "type": "webview", + "id": "lucisv.hierarchy", + "name": "Hierarchy" + } + ] + }, + "commands": [ + { + "command": "lucisv.hierarchy.refresh", + "title": "Refresh Hierarchy", + "icon": "$(refresh)" + }, + { + "command": "lucisv.hierarchy.clearBookmark", + "title": "Clear Hierarchy Bookmark", + "icon": "$(clear-all)" + } + ], + "menus": { + "view/title": [ + { + "command": "lucisv.hierarchy.refresh", + "when": "view == lucisv.hierarchy", + "group": "navigation@1" + }, + { + "command": "lucisv.hierarchy.clearBookmark", + "when": "view == lucisv.hierarchy", + "group": "navigation@2" + } + ] + }, "configurationDefaults": { "[verilog]": { "editor.defaultColorDecorators": "never" diff --git a/editors/vscode/smoke.js b/editors/vscode/smoke.js index e51b14b..8adbd60 100644 --- a/editors/vscode/smoke.js +++ b/editors/vscode/smoke.js @@ -94,6 +94,7 @@ server.stdin.end( params: { processId: process.pid, rootUri: null, + initializationOptions: { hierarchyView: true }, capabilities: { textDocument: { rangeFormatting: { dynamicRegistration: true, rangesSupport: true } } }, }, }), @@ -110,6 +111,9 @@ server.stdin.end( params: { textDocument: { uri: brokenUri, languageId: 'systemverilog', version: 1, text: BROKEN } }, }), frame({ jsonrpc: '2.0', id: 5, method: 'lucisv/scopePairs', params: { textDocument: { uri: brokenUri } } }), + // The custom sidebar snapshot. The opened source contributes one module; + // this catches a server/extension method-name or response-shape mismatch. + frame({ jsonrpc: '2.0', id: 8, method: 'lucisv/moduleHierarchy', params: {} }), // Ghost text, just after the `begin` on line 2 of the buffer that lost its // `end`. The extension only ever sends this after opting into // `ProposedFeatures`, so an "unhandled method" here is the same kind of @@ -178,6 +182,20 @@ server.on('close', (code) => { if (!capabilities.documentHighlightProvider) fail('capability missing: documentHighlightProvider'); if (!capabilities.inlineCompletionProvider) fail('capability missing: inlineCompletionProvider'); + const hierarchy = messages.find((m) => m.id === 8); + if (!hierarchy || hierarchy.error) fail(`hierarchy snapshot failed: ${JSON.stringify(hierarchy)}`); + if (!hierarchy.result || hierarchy.result.schemaVersion !== 2) fail('hierarchy snapshot has the wrong schema'); + if (!Array.isArray(hierarchy.result.files)) fail('hierarchy snapshot has no file table'); + const hierarchyNames = (hierarchy.result.modules || []).map((module) => module.moduleName); + if (!hierarchyNames.includes('top')) fail(`hierarchy snapshot missing top: ${JSON.stringify(hierarchyNames)}`); + // A location names its file by index and its ranges as four numbers — the + // narrow wire the sidebar's cost fix introduced. + const definition = (hierarchy.result.modules.find((m) => m.moduleName === 'top') || {}).definition; + if (!definition || typeof definition.file !== 'number' + || !Array.isArray(definition.range) || definition.range.length !== 4) { + fail(`hierarchy definition is not the narrow shape: ${JSON.stringify(definition)}`); + } + const diagnostics = messages.find((m) => m.method === 'textDocument/publishDiagnostics'); if (!diagnostics) fail('the server pushed no diagnostics for the opened document'); diff --git a/topo.md b/topo.md index 95c34d0..5aad682 100644 --- a/topo.md +++ b/topo.md @@ -413,6 +413,9 @@ promise: | `index-persistence ──▶ format-cache` (lucisv_core) | depends | Reuses `lucisv_core::cache::content_hash` — one FNV-1a shared with the format cache, not a second copy. Also one additive `vlog_parser` touch: `DefineTable::from_entries` + `PartialEq`/`Eq` derives, so a record restores a table without re-reading a file. | | `index-persistence ◀──▶ indexing-ux` | handshake | `IndexEvent::Cached` — a new variant, so every consumer is forced to say what it does with an unparsed file; the end message names the cached count. | | `port-detail-spans ◀──▶ index-persistence` | handshake | A declaration record grew two numbers (the detail span, written unconditionally as `0 0` for the `None` every ordinary declaration has), so **`FACTS_FORMAT` went 2 → 3** and every store written by an earlier build is discarded whole rather than read field-shifted. The bump *is* the contract: `index_cache.rs`'s header line carries the number, and the reader's `done()` check is a backstop, not a version scheme. | +| `vscode-hierarchy-sidebar ◀──▶ index-persistence / hover-line-index / incremental-index` | handshake | **`FACTS_FORMAT` 4 → 5**, one bump for three additions: `Def::decl_span`; `InstantiationEdge::instances` (a `Vec` — the statement edge stays one-per-statement, so call hierarchy and code-lens counts are unchanged and the census is still the one `instantiations::sites` walk); and client positions — `DeclLines::positions: Option` on **file-scope declarations only**, plus `Utf16Range` on every instance occurrence. Members deliberately carry none: they outnumber units by two orders of magnitude, and the `U`/`M` groups are separate, so a member costs no field at all. `FileFacts::from_analysis` grew a `src: &str` parameter (a position cannot be read off a line table). Measured store cost of the positions: +1.69 % on the 820-file corpus, +1.86 % on opentitan. | +| `vscode-hierarchy-sidebar ──▶ vlog_parser` | depends | `LineIndex::utf16_position` — byte offset to (0-based line, UTF-16 column), moved down beside the line table so the semantic index and `lucisv_server::convert::Positions` cannot answer differently. `Positions::position` is now a wrapper over it; the cross-crate equality is test-pinned. | +| `vscode-hierarchy-sidebar ◀──▶ workspace-index` | handshake | `WorkspaceIndex::units_of(kind)` — file-scope declarations of one kind, in name order, walking the unit table alone. The cheap half of `workspace_symbols("")` for a caller that never wants members; 15 ms per snapshot on opentitan. | | `hover-line-index ──▶ port-detail-spans / index-persistence` | depends + handshake | `DeclLines { name, detail }` rides each indexed `Decl`, so ordinary and split-port hover headings do not reread a file just to compute a line. The record grew again and **`FACTS_FORMAT` went 3 → 4**; the server's bounded `FileView` cache supplies the text/`LineIndex` only when a snippet or a non-indexed position still needs it. Its four invalidation points are `set_document`, `close_document`, `update_one`, and a whole rebuild. | | `scan-interleave ◀──▶ workspace-index` | handshake | A scan is a stepped `Scan` value; staged `FileFacts` land through `WorkspaceIndex::absorb`, one whole-index merge per queue drain rather than per file. `Candidates::absorb` and `IncludeGraph::absorb` publish their tables in the same drain, so “the workspace as far as scanned” cannot mean three different prefixes. | | `scan-interleave ──▶ hover-line-index` | depends | Delivers hover-line-index's measured startup-wait request: a startup scan above 64 files drains queued messages between files. A rescan deliberately still holds requests; what an answer sees never depends on elapsed wall time. | @@ -475,6 +478,9 @@ engine-lane features are listed above; this table is the server-internal web. | `selection-range / linked-editing ──▶ spans, name-spans` | depends | Pure arrangements of existing ranges; linked-editing's table documents exactly which constructs carry both spans (and which verbatim ones can't — `program`, property/sequence, covergroup). | | `type-definition ──▶ nav / overlay-promotion / ansi-first-port` | depends + 2 delivered handshakes | Now literally `nav::definition` at the type name's offset; both of its filed requests landed (§2.2, §2.5). | | `hierarchy ◀──▶ inlay-hints` | handshake (shared walk) | The instantiation walk was lifted out of `inlay.rs` into a shared module (now `vlog_semantic::instantiations`) rather than copied — the two answers cannot drift; inlay's 34 tests are the regression net. | +| `vscode-hierarchy-sidebar ◀──▶ editors/vscode` | handshake | Two custom wire members, both **gated on `initializationOptions.hierarchyView`** so no other LSP client sees them: the request `lucisv/moduleHierarchy` → a flat `schemaVersion: 2` snapshot (`files` table; locations as `{ file, range, selectionRange }` with each range `[startLine, startCharacter, endLine, endCharacter]`; **no** per-row id and **no** per-instance `definitions` — the client composes both in `hierarchyModel.js::validateSnapshot`), and the notification `lucisv/moduleHierarchyChanged { revision }`. `revision` rises on every completed index install; the notification rides beside the code-lens refresh point so all mutation paths are covered once. An older binary answers `-32601`, which the view renders as a compatibility message. | +| `vscode-hierarchy-sidebar ◀──▶ code-lens / hierarchy` | handshake | Both read the *same* statement-level `InstantiationEdge`; only the sidebar flattens `edge.instances`, so `sub u1 (), u2 ();` is still one call site and one lens count and two sidebar rows. No second census exists. | +| `vscode-hierarchy-sidebar ──▶ scan-interleave / cancel-request` | depends | `complete` is `Server::index_is_complete()` = `!scanning && !must_wait()`. It is false exactly during the startup scan: a request owed a rescan is *held* by `must_wait`, and `rescan_wanted` is only ever set while `scanning` is true, so no snapshot is ever answered `complete` off an index a queued message is about to rebuild. | | `code-lens ◀──▶ hierarchy` | handshake | code-lens split `incoming` into the batch primitive `callers_of_each` so lens and hierarchy share one census; `incoming` is a one-element call into it and its behavior (empty-name guard included) is pinned unchanged. Lens and hierarchy views can never disagree; refresh rides `reindex()` after the bar comes down. | | `server-lint / pull-diagnostics / editor-scopes ──▶ diagnostics.rs` | depends | One `diagnostics::all` composition: parse errors + missing-closer warnings + lint warnings, one publish (or one pull) per change; `send_diagnostics` is the single push gate so a pulling client is never served both models. |