diff --git a/TODO.md b/TODO.md index 6d3049a..6ebfcf3 100644 --- a/TODO.md +++ b/TODO.md @@ -1233,19 +1233,26 @@ Files: `crates/lucisv_server/src/{candidates.rs,state.rs,server.rs,perf.rs}`, ### Deferred, filed -- [ ] `codeAction` costs 185–201 ms at a 128-file fan-out and offers +- [x] `codeAction` costs 185–201 ms at a 128-file fan-out and offers **zero** actions there (`performance_take2.md` §6a): ~1.4 ms per instantiating file plus a ~13 ms floor, paid before anything knows there is nothing to offer. Wants either the lazy resolve below or a cheap zero-detector that answers before the fan-out is walked. -- [ ] `inlayHint` returns **0 hints at the default scope** where the + **Delivered by §37.1**: the offer is flat at 54–59 µs from a 3- to a + 128-file fan-out, both cursor shapes. +- [x] `inlayHint` returns **0 hints at the default scope** where the workspace scope returns 4 (`performance_take2.md` §8): investigate before assuming it is scope-relative-answers working as intended — the hinted instantiation's module may be in scope and still unhinted. -- [ ] codeAction lazy resolution (`codeAction/resolve`): make the offer + **Investigated by §37.2 and ruled correct**: the four hints are + `pins_if`'s, declared in `hw/dv/sv/common_ifs`, which the widen to + `hw/ip/aes` does not reach; hover and definition answer nothing for it + either. Finding and two default-scope tests in + `docs/features/lazy-code-action/README.md`. +- [x] codeAction lazy resolution (`codeAction/resolve`): make the offer index-only (~0 ms regardless of fan-out), edits computed on lightbulb click — kills the 83 ms worst case. Owner-approved - direction, after the wave. + direction, after the wave. **Delivered by §37.1.** - [x] Rename over an index-stale workspace: Lane A must state the staleness premise; if the verifier cannot catch a hidden reference, the honesty gate is the lead's review call. Stated @@ -1290,10 +1297,17 @@ and three owner items. See 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` +- [x] 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. + unit's range is now in the index for free. **Delivered by §37.3** + for the file-scope answers `nav.rs` and `symbols.rs` give + (27.9 µs → 0.42 µs per definition on opentitan); references, the + lens and the hierarchies answer from `ReferenceSite`/`InstantiationEdge` + spans, which are not `Def`s and record no `DeclPositions`, and + `references`' one `Def` span (`includeDeclaration`) is converted in the + same one-fetch batch as that file's reference sites — filed again + there rather than silently dropped. - [ ] Manual extension-host acceptance (themes, keyboard-only, zoom, screen readers, an old server binary, both VSIX shapes). @@ -3999,3 +4013,111 @@ opentitan read-only sweep, vsix smoke, 0.40.0. `mismatched-labels` had no arm for the block; fixed by the lead at review with a test, plus the LOW doc comment and a read-only-target refusal in `write_atomic` (parity with the old `fs::write`) + +## 37. Server residue from §10 (planned 2026-09-04) — lazy codeAction resolve, the inlayHint zero, `locate` onto `DeclPositions` + +One lane in the main tree, dev Opus 5 then QA Sonnet 5, same protocol as +§36 (lead snapshots the diff before QA; QA never runs a git command that +rewrites the tree). Feature README: `docs/features/lazy-code-action/README.md` +(one README for the three, sections per item). Ships as 0.41.0. + +**Expected touch set:** `crates/lucisv_server/src/{ports.rs,code_action.rs, +locate.rs,nav.rs,symbols.rs,inlay.rs,main.rs,state.rs,perf.rs}`, +`crates/lucisv_server/src/server/{dispatch.rs,mod.rs}`, +`crates/lucisv_server/tests/e2e.rs`, `crates/vlog_refactor/src/ports/mod.rs` +(only if the offer needs a new one-file question), the §10 lines this closes +(1236–1249 and 1293), `docs/features/server-lint/README.md`'s resolve note, +this section. Anything else is named in the work log. + +### 37.1 `codeAction/resolve` for the port refactorings (§10, owner-approved) + +`ports::code_actions` costs ~1.4 ms per instantiating file plus a 13 ms +floor on every cursor move (`docs/performance_take2.md` §6a: 185 ms at a +128-file fan-out, to offer zero actions), because the *offer* already +computes the full edit over `Workspace::module_sources` — the module's +fan-out **plus every open buffer**, each read as text. The quick fixes in +`code_action.rs` are cheap and stay eager; only the port actions change. + +- **The offer is local.** Whether an action exists at the cursor is a + one-file question plus, for a cursor on an instantiation, the instantiated + module's own declaration (`vlog_refactor::module_definition` through the + index — one file, the way `inlay.rs`'s `Plans::read` does it). Run the + engine's `port_actions` over exactly those sources to learn which actions + exist; throw the edits away. No fan-out is read. The title's count + ("updates N instantiations") comes from the index + (`instantiations_of(name)` — say in the doc whether that is instances or + files, and word the title to match); the unsaved-buffer case in + `an_unsaved_buffer_contributes_the_instantiation_the_index_has_not_seen` + is answered by the *resolved* edit, which is still exact — move that pin + to resolve. +- **Resolve computes the edit.** Each offered action carries `data` + (`{uri, position, title}`) and no `edit`. `codeAction/resolve` re-runs + today's eager path at that position and returns the action whose title + matches, with its `edit`. No match (the buffer changed under the + lightbulb) is an error response, `"the action is no longer available"`, + not a silent empty edit. Advertise `resolve_provider: Some(true)`. +- **A client that cannot resolve gets today's answer.** Read + `textDocument.codeAction.resolveSupport.properties` at `initialize`; only + when it lists `"edit"` is the offer lazy. Keep the flag in the server + state beside whatever `main.rs` already reads from the client + capabilities (the range-formatting registration is the precedent). +- Tests: the lazy offer's titles and kinds equal the eager offer's, over + the `crowded` tree; the resolved `WorkspaceEdit` is byte-equal to the + eager one (both cursor shapes: a port declaration, an instantiation with + missing connections); the no-resolveSupport client gets the eager shape; + a resolve after the document changed errors; the offer over + `crowded(40)` reads none of the noise files and none of the fan-out + (pin it the way `the_files_a_code_action_reads_are_the_modules_own_fan_out` + pins the eager path — through what the offer asks the workspace for); + an e2e case over the wire (`tests/e2e.rs`): initialize with + resolveSupport → `codeAction` returns `data` and no `edit` → + `codeAction/resolve` returns the edit; initialize without → the edit is + inline. `perf.rs`'s `a_code_action_at_an_instantiation_before_and_after` + gains an "offer" column; report the three numbers in the work log. + +### 37.2 `inlayHint` returns 0 at the default scope where workspace scope returns 4 (§10 / take-2 §8) + +Investigate before fixing: `Plans::read` asks `module_definition` of the +index, and at folder or default scope the instantiated module's file may +not be in the index even though §4b says the default scope now answers +cross-file questions (the `didOpen` widen). Find which lookup the +neighbours (hover, signature help, completion) use that inlay does not, +and make inlay use it. Deliverable is one of: a fix with a test at the +default scope (a `sub.sv` outside the opened folder, `top.sv` inside it, +hints appear after the widen), or — if the zero is correct — a paragraph +in the README saying exactly why, for the lead to rule on. Not a gate. + +### 37.3 `locate::location` onto `DeclPositions` (§10, filed) + +`Def::lines.positions` (`DeclPositions { name, decl }`, `Some` for every +file-scope declaration) already holds the client-side ranges, so +`textDocument/definition`, references, the lens and both hierarchies need +not read a file to convert an indexed span. Add the index-only path in +`locate.rs` for a `Def` whose positions are recorded (members keep the +file-read path — they have none) and route `nav.rs`/`symbols.rs`'s +file-scope answers through it. Pins: the index-only `Location` equals the +file-read one over files with multi-byte and astral characters (UTF-16 +surrogates), CRLF and a BOM; a file-scope definition answers without a +`file_view` being created (assert through whatever the view cache exposes, +or add a test-only counter — say which); a definition request over an +opentitan file timed before/after, read-only, in the work log. + +### Gates (dev, guarded) + +`cargo fmt -p` per touched crate; clippy clean; `tools/guard.sh -- cargo +test --workspace`; `tools/guard.sh -- tools/corpus_check.sh` unchanged +(814/820, same six); the e2e suite green; vsix smoke. Lead at review: +byte-identity vs 0.40.0, opentitan read-only sweep, 0.41.0. + +- [x] 37.1 lazy offer + resolve + capability gate + e2e + perf column +- [x] 37.2 inlayHint: fix with test, or the written finding — the written + finding (the zero is correct), plus two default-scope tests +- [x] 37.3 `locate` index-only path + pins + timing +- [x] docs: feature README; §10 lines ticked; server-lint note +- [x] Gates (guarded) +- [x] QA: resolve attacked (stale document, wrong data, missing data, + client without resolveSupport, both cursor shapes, unsaved buffer); + inlay at the default scope against a real two-folder tree; locate + equality over the encoding shapes; opentitan timing re-derived — + PASS, no findings above LOW; offer ~4.5 ms vs eager ~77 ms over the + wire at the 128-file fan-out diff --git a/crates/lucisv_server/src/inlay.rs b/crates/lucisv_server/src/inlay.rs index a3eed84..a5e5e78 100644 --- a/crates/lucisv_server/src/inlay.rs +++ b/crates/lucisv_server/src/inlay.rs @@ -755,6 +755,92 @@ endmodule assert_eq!(labels, ["clk_renamed:", "rst_n:", "data:"]); } + // ------------------------------------------------------------------ + // the default scope (TODO §37.2 / `performance_take2.md` §4b, §8) + // ------------------------------------------------------------------ + + /// An opentitan-shaped tree: an IP block with its RTL and its testbench, + /// and a shared library folder outside that block. Opening + /// `ip/aes/dv/tb/tb.sv` at the shipped `scopeDepth` of 2 raises to + /// `ip/aes`, so `ip/aes/rtl/sub.sv` is indexed and `dv/common/far.sv` is + /// not — which is exactly the shape `hw/ip/aes/dv/tb/tb.sv` has against + /// `hw/dv/sv/common_ifs/pins_if.sv`. + fn default_scoped(name: &str) -> (Tree, Workspace, Uri, &'static str) { + const TB: &str = + "module tb;\n sub u_sub (clk, rst_n, data);\n far u_far (a);\nendmodule\n"; + let tree = Tree::new(name); + fs::create_dir_all(tree.path.join("ip/aes/rtl")).expect("dirs"); + fs::create_dir_all(tree.path.join("ip/aes/dv/tb")).expect("dirs"); + fs::create_dir_all(tree.path.join("dv/common")).expect("dirs"); + tree.write("ip/aes/rtl/sub.sv", SUB); + tree.write("dv/common/far.sv", "module far (\n input logic a\n);\nendmodule\n"); + let tb = tree.write("ip/aes/dv/tb/tb.sv", TB); + + let mut ws = Workspace::default(); + // The shipped default: no `index.scope`, `scopeDepth` 2. + ws.set_client_settings(crate::settings::ClientSettings::default()); + ws.adopt_roots(vec![tree.path.clone()]); + let uri = path_to_uri(&tb).expect("uri"); + ws.set_document(uri.clone(), TB.to_string()); + ws.rebuild_index(); + (tree, ws, uri, TB) + } + + #[test] + fn the_default_scope_hints_a_module_the_didopen_widen_reached() { + // `performance_take2.md` §4b measured 0 hints at the default scope + // where the workspace scope gives 4, and §8 filed it as a correctness + // gap. It is not one: the hints that scope answers are exactly the + // instantiations whose module the widen reached. + let (tree, ws, uri, _) = default_scoped("default_scope"); + assert!( + ws.index().files().iter().any(|f| f.ends_with("sub.sv")), + "the widen reached the block's own RTL: {:?}", + ws.index().files() + ); + assert!( + !ws.index().files().iter().any(|f| f.ends_with("far.sv")), + "and not the library folder beside it" + ); + + let hints = inlay_hints(&ws, &uri, everything()); + let labels: Vec = hints + .into_iter() + .map(|h| { + let InlayHintLabel::String(s) = h.label else { panic!("string") }; + s + }) + .collect(); + assert_eq!(labels, ["clk:", "rst_n:", "data:"], "the in-scope instantiation is hinted"); + drop(tree); + } + + #[test] + fn an_out_of_scope_module_is_unhinted_exactly_as_it_is_undefined() { + // The other half of the same finding: the `far` instantiation gets no + // hints — and go-to-definition and hover give nothing for it either. + // The zero is the scope's, not this module's; inlay uses the same + // `module_definition` lookup its neighbours do. + let (tree, ws, uri, tb) = default_scoped("out_of_scope"); + let hints = inlay_hints(&ws, &uri, everything()); + assert!( + hints.iter().all(|hint| hint.position.line != 2), + "nothing on the `far` line: {hints:#?}" + ); + + let far = tb.find("far u_far").expect("the instantiation") as u32; + assert!(crate::nav::definition(&ws, &uri, far).is_empty(), "nor does F12 answer"); + assert!(crate::hover::hover(&ws, &uri, far).is_none(), "nor does hover"); + + // And the moment the scope reaches it, all three answer. + let mut wide = Workspace::default(); + wide.open_whole_workspace(vec![tree.path.clone()]); + wide.set_document(uri.clone(), tb.to_string()); + let hints = inlay_hints(&wide, &uri, everything()); + assert_eq!(hints.len(), 4, "three ports plus `far`'s one: {hints:#?}"); + assert_eq!(crate::nav::definition(&wide, &uri, far).len(), 1); + } + /// Order-of-magnitude perf checks, not run as part of the ordinary suite: /// timing assertions in a shared CI runner are flaky by nature. Run with /// `cargo test --release -p lucisv_server --bin lucisv-server qa_perf -- --ignored --nocapture`. diff --git a/crates/lucisv_server/src/locate.rs b/crates/lucisv_server/src/locate.rs index 7eefcc3..d9b2233 100644 --- a/crates/lucisv_server/src/locate.rs +++ b/crates/lucisv_server/src/locate.rs @@ -7,11 +7,18 @@ //! buffer's own line index when there is one, and otherwise through //! `Workspace::file_view`, which reads a closed file at most once per //! generation of it rather than once per question about it. +//! +//! One span never needs that read at all: a **file-scope declaration**'s own +//! name, whose client-side range the index recorded when the file was scanned +//! ([`vlog_semantic::DeclPositions`]). [`definition_location`] is that path, +//! and it is what `textDocument/definition` and `workspace/symbol` answer +//! from — see `docs/features/lazy-code-action/README.md`. use std::path::Path; -use lsp_types::Location; +use lsp_types::{Location, Position, Range}; use vlog_parser::TextRange; +use vlog_semantic::{Def, Utf16Range}; use crate::convert::Positions; use crate::state::Workspace; @@ -27,6 +34,40 @@ pub fn location(ws: &Workspace, path: &Path, span: TextRange) -> Option Option { + if ws.document_for_path(path).is_none() { + if let Some(recorded) = def.lines.positions { + return Some(Location { uri: path_to_uri(path)?, range: range(recorded.name) }); + } + } + location(ws, path, def.name_span) +} + +/// An index-recorded range as the protocol's own — the same four numbers, +/// both already counted in UTF-16 code units by the file's own +/// `LineIndex::utf16_position`, which is the converter `Positions` uses too. +fn range(recorded: Utf16Range) -> Range { + Range { + start: Position { line: recorded.start.line, character: recorded.start.character }, + end: Position { line: recorded.end.line, character: recorded.end.character }, + } +} + /// The 1-based line a byte offset falls on, for hover text that names a file /// and a line rather than jumping to it. /// @@ -49,3 +90,197 @@ pub fn line_number(ws: &Workspace, path: &Path, offset: u32) -> Option { pub fn display_name(path: &Path) -> String { path.file_name().and_then(|n| n.to_str()).unwrap_or("?").to_string() } + +#[cfg(test)] +mod tests { + use super::*; + use std::fs; + use std::path::PathBuf; + + /// A scratch workspace root. Removed on drop. + struct Tree { + path: PathBuf, + } + + impl Tree { + fn new(name: &str) -> Tree { + let path = std::env::temp_dir() + .join(format!("lucisv_server_locate_{}_{name}", std::process::id())); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("temp dir"); + Tree { path } + } + + /// Write a file as **bytes**, so a test can put a BOM or CRLF in one. + fn write(&self, rel: &str, text: &str) -> PathBuf { + let path = self.path.join(rel); + fs::write(&path, text.as_bytes()).expect("write"); + path + } + + /// An indexed workspace over everything written so far. + fn indexed(&self) -> Workspace { + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![self.path.clone()]); + ws + } + } + + impl Drop for Tree { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + } + } + + /// The one declaration of `name` in the index, and the file it is in. + fn only_def<'w>(ws: &'w Workspace, name: &str) -> (&'w Def, &'w Path) { + let index = ws.index(); + let [def] = index.units(name) else { panic!("exactly one `{name}`") }; + (def, index.path(def.file).expect("a path")) + } + + #[test] + fn a_file_scope_definition_is_located_without_reading_its_file() { + let tree = Tree::new("no_read"); + tree.write("sub.sv", "module sub (\n input logic clk\n);\nendmodule\n"); + let ws = tree.indexed(); + let (def, path) = only_def(&ws, "sub"); + + let indexed = definition_location(&ws, path, def).expect("a location"); + assert!(ws.held_views().is_empty(), "no file was read: {:?}", ws.held_views()); + + // Only now, so the comparison cannot be what filled the cache. + let read = location(&ws, path, def.name_span).expect("a location"); + assert_eq!(indexed, read); + assert_eq!(ws.held_views().len(), 1, "the file-read path really does read one"); + } + + #[test] + fn the_two_paths_agree_over_multi_byte_astral_crlf_and_a_bom() { + // Everything that has ever made a UTF-16 conversion disagree, in one + // file: a BOM at offset 0, CRLF line endings, a two-byte character, a + // three-byte one, and an astral character that is *two* UTF-16 code + // units on its own. + let tree = Tree::new("encodings"); + tree.write( + "wide.sv", + "\u{feff}// é ✓ 𝛼𝛽 — a comment\r\n\ + // 𝟘𝟙𝟚 more\r\n\ + module wide (\r\n input logic clk\r\n);\r\nendmodule\r\n", + ); + let ws = tree.indexed(); + let (def, path) = only_def(&ws, "wide"); + + let indexed = definition_location(&ws, path, def).expect("a location"); + assert!(ws.held_views().is_empty(), "still no read"); + let read = location(&ws, path, def.name_span).expect("a location"); + assert_eq!(indexed, read, "the index-only range must be the file-read one"); + // And it really is the name, not the line: `module ` is seven UTF-16 + // units into line 2 (0-based), whatever the lines above it hold. + assert_eq!(indexed.range.start.line, 2); + assert_eq!(indexed.range.start.character, 7); + assert_eq!(indexed.range.end.character, 11); + } + + #[test] + fn an_open_buffer_still_answers_from_the_buffer() { + // The index saw the file on disk; the buffer has since gained a line + // above the declaration, and has not been re-indexed. An indexed span + // is stale either way — the byte offset is the disk file's — and what + // this pins is that the *conversion* is unchanged by this round: the + // buffer's own line index, exactly as before, so go-to-definition and + // the document symbols beside it still agree with each other. + let tree = Tree::new("open_buffer"); + let path = tree.write("sub.sv", "module sub;\nendmodule\n"); + let mut ws = tree.indexed(); + let uri = crate::uri::path_to_uri(&path).expect("uri"); + ws.set_document(uri, "// typed since\nmodule sub;\nendmodule\n".to_string()); + + let (def, path) = only_def(&ws, "sub"); + let located = definition_location(&ws, path, def).expect("a location"); + assert_eq!( + located, + location(&ws, path, def.name_span).expect("a location"), + "an open buffer takes the file-read path, index positions or not" + ); + assert_eq!(located.range.start.line, 0, "byte 7 of the buffer, not of the index's file"); + assert!(ws.held_views().is_empty(), "an open buffer is never viewed"); + } + + #[test] + fn a_member_keeps_the_file_read_path() { + // Members carry no `DeclPositions` — see `DeclLines` — so the fallback + // is not decoration: it is the only answer for a port. + let tree = Tree::new("member"); + tree.write("sub.sv", "module sub (\n input logic clk\n);\nendmodule\n"); + let ws = tree.indexed(); + let index = ws.index(); + let [port] = index.member("sub", "clk") else { panic!("one `clk`") }; + assert!(port.lines.positions.is_none(), "a member records no client positions"); + let path = index.path(port.file).expect("a path"); + assert_eq!( + definition_location(&ws, path, port), + location(&ws, path, port.name_span), + "and the fallback answers exactly what it always did" + ); + assert_eq!(ws.held_views().len(), 1, "which cost the read"); + } + + /// `LUCISV_PERF_CORPUS=/path/to/project cargo test --release -p lucisv_server --bin lucisv-server locate::tests::defining -- --ignored --nocapture --test-threads=1` + #[test] + #[ignore = "perf measurement over a corpus this repository does not ship — see docs/perf/README.md"] + fn defining_over_a_real_project() { + // TODO §37.3's own number, beside the code it measures rather than in + // `perf.rs` — the precedent `perf::mean`'s `pub(crate)` exists for. + // Two columns over the same corpus and the same targets: converting an + // indexed span by reading its file, and reading it off the index. + // **Read-only** — the corpus is opened, never written. + let Ok(root) = std::env::var("LUCISV_PERF_CORPUS") else { + eprintln!("LUCISV_PERF_CORPUS is unset — nothing to measure"); + return; + }; + let mut ws = Workspace::default(); + ws.set_client_settings(crate::settings::ClientSettings { + index_scope: crate::settings::IndexScope::Workspace, + ..Default::default() + }); + let started = std::time::Instant::now(); + ws.open_whole_workspace(vec![PathBuf::from(&root)]); + let scan = started.elapsed(); + + // The targets: modules the corpus instantiates somewhere, whose single + // declaration the index can name — what an F12 on an instantiation + // lands on, and each in a different file. + let names: Vec = + ws.index().instantiations().map(|(name, _)| name.to_string()).collect(); + let targets: Vec<(PathBuf, vlog_semantic::Def)> = names + .iter() + .filter_map(|name| { + let path = vlog_refactor::module_definition(ws.index(), name).ok()?; + let [def] = ws.index().units(name) else { return None }; + def.lines.positions.is_some().then(|| (path.to_path_buf(), def.clone())) + }) + .take(200) + .collect(); + + let indexed = crate::perf::mean(5, || { + for (path, def) in &targets { + std::hint::black_box(definition_location(&ws, path, def)); + } + }); + let read = crate::perf::mean(5, || { + for (path, def) in &targets { + std::hint::black_box(location(&ws, path, def.name_span)); + } + }); + let each = targets.len().max(1) as u32; + eprintln!( + "definition over {} indexed files of {root} (scan {scan:?}), {} targets:\n \ + index-only {indexed:?}, file-read {read:?} — {:?} vs {:?} per definition", + ws.index().files().len(), + targets.len(), + indexed / each, + read / each, + ); + } +} diff --git a/crates/lucisv_server/src/main.rs b/crates/lucisv_server/src/main.rs index 27683a2..9609b43 100644 --- a/crates/lucisv_server/src/main.rs +++ b/crates/lucisv_server/src/main.rs @@ -126,6 +126,7 @@ fn main() -> Result<(), Box> { configuration: configuration_support(¶ms), token_server_cancel: token_server_cancel_support(¶ms), hierarchy_view, + code_action_resolve: code_action_resolve_support(¶ms), }; connection.initialize_finish(id, initialize_value(ranges_formatting)?)?; @@ -261,8 +262,13 @@ fn capabilities() -> ServerCapabilities { CodeActionKind::new(ports::REFACTOR_PORTS), ]), work_done_progress_options: WorkDoneProgressOptions::default(), - // Every action is returned complete; there is nothing to resolve. - resolve_provider: None, + // The quick fixes are complete when they are offered; the port + // refactorings are not, for a client that can ask + // (`docs/features/lazy-code-action/README.md`). Advertised + // unconditionally because the server can always answer a resolve + // — including for an action that already carries its edit, which + // it hands straight back. + resolve_provider: Some(true), })), // The port refactorings. `lucisv.addPort` needs a declaration typed by // the user, which no code action can carry, and a Vim user has no @@ -499,6 +505,24 @@ fn snippet_support(params: &InitializeParams) -> bool { .unwrap_or(false) } +/// Whether the client can fetch a code action's `edit` after the fact — +/// `textDocument.codeAction.resolveSupport.properties` listing `"edit"`. +/// +/// The property list is the capability: a client that can resolve `title` +/// alone cannot be offered an action without its edit, so nothing short of +/// `"edit"` counts. A client that says nothing gets every action complete, as +/// every client did before this was read +/// (`docs/features/lazy-code-action/README.md`). +fn code_action_resolve_support(params: &InitializeParams) -> bool { + params + .capabilities + .text_document + .as_ref() + .and_then(|text_document| text_document.code_action.as_ref()) + .and_then(|code_action| code_action.resolve_support.as_ref()) + .is_some_and(|resolve| resolve.properties.iter().any(|property| property == "edit")) +} + /// Whether the client applies a `workspace/applyEdit` request. /// /// A client that did not say so gets a command's edit back as the request @@ -1148,6 +1172,46 @@ mod tests { assert!(kinds.contains(&CodeActionKind::QUICKFIX)); assert!(kinds.contains(&CodeActionKind::new(code_action::FIX_ALL))); assert!(kinds.contains(&CodeActionKind::new(ports::REFACTOR_PORTS))); + assert_eq!( + options.resolve_provider, + Some(true), + "the port refactorings are offered without their edits to a client that can ask" + ); + } + + #[test] + fn code_action_resolve_support_is_read_from_the_clients_own_capabilities() { + use lsp_types::{ + ClientCapabilities, CodeActionCapabilityResolveSupport, CodeActionClientCapabilities, + TextDocumentClientCapabilities, + }; + assert!( + !code_action_resolve_support(&InitializeParams::default()), + "silence means the whole edit up front" + ); + + let saying = |properties: &[&str]| InitializeParams { + capabilities: ClientCapabilities { + text_document: Some(TextDocumentClientCapabilities { + code_action: Some(CodeActionClientCapabilities { + resolve_support: Some(CodeActionCapabilityResolveSupport { + properties: properties.iter().map(|p| p.to_string()).collect(), + }), + ..Default::default() + }), + ..Default::default() + }), + ..Default::default() + }, + ..Default::default() + }; + assert!(code_action_resolve_support(&saying(&["edit"]))); + assert!(code_action_resolve_support(&saying(&["documentation", "edit"]))); + assert!( + !code_action_resolve_support(&saying(&["documentation"])), + "resolving anything but the edit is no use to us" + ); + assert!(!code_action_resolve_support(&saying(&[]))); } #[test] diff --git a/crates/lucisv_server/src/nav.rs b/crates/lucisv_server/src/nav.rs index 851187f..97b9642 100644 --- a/crates/lucisv_server/src/nav.rs +++ b/crates/lucisv_server/src/nav.rs @@ -7,7 +7,7 @@ use vlog_semantic::{Def, Definition, ExternalTarget, Semantics, Symbol, SymbolId use crate::convert::Positions; use crate::includes; -use crate::locate::location; +use crate::locate::{definition_location, location}; use crate::state::{Document, Workspace}; use crate::uri::path_to_uri; @@ -60,7 +60,9 @@ pub fn definition(ws: &Workspace, uri: &Uri, offset: u32) -> Vec { .iter() .filter_map(|def| { let path = ws.index().path(def.file)?; - location(ws, path, def.name_span) + // A file-scope declaration's range is already in the index, so + // the jump costs no read of the file it lands in. + definition_location(ws, path, def) }) .collect(), None => Vec::new(), @@ -691,6 +693,36 @@ mod tests { let _ = fs::remove_dir_all(&dir); } + #[test] + fn a_cross_file_definition_reads_no_file() { + // The jump above, asked again for what it *costs*: the target module's + // range is in the index (`DeclPositions`), so nothing opens `sub.sv`. + // Pinned through the view cache, which is where a read would land. + let dir = temp_dir("no_read"); + let sub = dir.join("sub.sv"); + fs::write(&sub, "module sub (input clk);\nendmodule\n").expect("write"); + let top_path = dir.join("top.sv"); + let top_text = "module top;\n sub u_sub (.clk(1'b0));\nendmodule\n"; + fs::write(&top_path, top_text).expect("write"); + + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let uri = path_to_uri(&top_path).expect("uri"); + ws.set_document(uri.clone(), top_text.to_string()); + + let locations = definition(&ws, &uri, at(top_text, "sub u_sub")); + assert_eq!(locations.len(), 1); + assert_eq!(locations[0].range.start.character, 7, "and it is still the right answer"); + assert!(ws.held_views().is_empty(), "no file was read: {:?}", ws.held_views()); + + // `workspace/symbol` answers the same way, over the same index. + let hits = crate::symbols::workspace_symbols(&ws, "sub"); + assert!(hits.iter().any(|hit| hit.name == "sub"), "{hits:#?}"); + assert!(ws.held_views().is_empty(), "nor did the symbol search"); + + let _ = fs::remove_dir_all(&dir); + } + #[test] fn an_ambiguous_workspace_name_returns_every_location() { let dir = temp_dir("ambig"); diff --git a/crates/lucisv_server/src/perf.rs b/crates/lucisv_server/src/perf.rs index 70bb846..f6c7ad0 100644 --- a/crates/lucisv_server/src/perf.rs +++ b/crates/lucisv_server/src/perf.rs @@ -1022,6 +1022,14 @@ fn a_code_action_at_an_instantiation_before_and_after() { let after = mean(20, || { black_box(crate::ports::code_actions(&ws, &uri, black_box(offset))); }); + // TODO §37.1's column: the *offer* a client that can resolve receives, + // which reads the buffer and — at an instantiation — one more file, + // whatever the fan-out is. The edit is computed by `resolve`, which is the + // `after` column above, once, when the user clicks. + let position = ws.document(&uri).expect("open").positions().position(offset); + let offer = mean(20, || { + black_box(crate::ports::offers(&ws, &uri, black_box(position), black_box(offset))); + }); let read = mean(3, || { black_box(ws.sources()); }); @@ -1035,9 +1043,10 @@ fn a_code_action_at_an_instantiation_before_and_after() { }); // A measurement of an answer that was not given is worthless. assert_eq!(crate::ports::code_actions(&ws, &uri, offset).len(), 1); + assert_eq!(crate::ports::offers(&ws, &uri, position, offset).len(), 1); eprintln!( "codeAction on a port of a module instantiated in 3 of {} files ({lines} lines each): \ - whole workspace {before:?}, fan-out {after:?} \ + whole workspace {before:?}, fan-out {after:?}, offer {offer:?} \ (`sources()` alone: {read:?}; prepareRename, untouched: {prepare:?})", ws.index().files().len() ); diff --git a/crates/lucisv_server/src/ports.rs b/crates/lucisv_server/src/ports.rs index 0c0e8a9..b42772e 100644 --- a/crates/lucisv_server/src/ports.rs +++ b/crates/lucisv_server/src/ports.rs @@ -12,6 +12,13 @@ //! and `lucisv.propagatePorts` take a position and exist for the same reason a //! Vim user has no lightbulb: a command works everywhere a keybinding does. //! See `docs/features/refactor-ports/README.md`. +//! +//! **Two shapes of code action.** A client that can resolve is *offered* +//! actions with no edit ([`offers`]) and asks for the edit when the user picks +//! one ([`resolve`]); a client that cannot gets the edit up front +//! ([`code_actions`]). The offer reads one or two files whatever the module's +//! fan-out is, which is the whole point — see +//! `docs/features/lazy-code-action/README.md`. // See `rename.rs` for why this is a `WorkspaceEdit`'s problem and not ours. #![allow(clippy::mutable_key_type)] @@ -22,6 +29,7 @@ use std::path::{Path, PathBuf}; use lsp_types::{ CodeAction, CodeActionKind, CodeActionOrCommand, Position, TextEdit, Uri, WorkspaceEdit, }; +use serde::{Deserialize, Serialize}; use serde_json::Value; use vlog_parser::LineIndex; use vlog_refactor::{ModuleRef, RefactorEdit}; @@ -48,6 +56,12 @@ pub fn commands() -> Vec { /// The port actions available at a position, each carrying its own computed /// edit — nothing to resolve, and nothing offered that would be refused. +/// +/// What a client without `codeAction/resolve` gets, and what [`resolve`] +/// re-runs to answer one that has. It reads the module's whole fan-out +/// ([`Workspace::module_sources`]), which is ~1.4 ms per instantiating file: +/// fine once, when the user has clicked, and not fine on every cursor move, +/// which is why [`offers`] exists. pub fn code_actions(ws: &Workspace, uri: &Uri, offset: u32) -> Vec { let Some(doc) = ws.document(uri) else { return Vec::new() }; let Some(path) = doc.path.clone() else { return Vec::new() }; @@ -76,6 +90,183 @@ pub fn code_actions(ws: &Workspace, uri: &Uri, offset: u32) -> Vec Vec { + let Some(doc) = ws.document(uri) else { return Vec::new() }; + let Some(path) = doc.path.clone() else { return Vec::new() }; + let modules = vlog_refactor::port_action_modules(&doc.text, offset); + // A name the workspace declares twice is a refusal the engine makes over + // the fan-out, where it can see both declarations. The offer cannot, so it + // asks the index the same question rather than offering an action that + // resolve would then decline. + if modules.is_empty() || modules.iter().any(|name| declared_twice(ws, name)) { + return Vec::new(); + } + let sources = offer_sources(ws, &path, &doc.text, &modules); + vlog_refactor::port_actions(&sources, &path, offset) + .into_iter() + .map(|action| { + let title = counted(ws, action.title, &modules); + let data = + serde_json::to_value(Offer { uri: uri.clone(), position, title: title.clone() }) + .ok(); + CodeActionOrCommand::CodeAction(CodeAction { + title, + kind: Some(CodeActionKind::new(REFACTOR_PORTS)), + data, + ..Default::default() + }) + }) + .collect() +} + +/// The files an [`offers`] call reads: the buffer the request names, and the +/// declaration of every module an instantiation under the cursor names. +/// +/// The second is the same two steps `inlay.rs`'s `Plans::read` takes — the +/// index says which file declares the module, and that one file is read — +/// and it is what lets the engine answer "this instantiation is missing +/// ports" without any file that *instantiates* the module. A cursor on a port +/// declaration names its own module, whose declaring file is the buffer +/// itself, so that case reads nothing at all. +/// +/// `pub(crate)` for the test that pins exactly this set. +pub(crate) fn offer_sources( + ws: &Workspace, + path: &Path, + text: &str, + modules: &[String], +) -> Vec<(PathBuf, String)> { + let mut sources = vec![(path.to_path_buf(), text.to_string())]; + for name in modules { + let Ok(declared_in) = vlog_refactor::module_definition(ws.index(), name) else { continue }; + if sources.iter().any(|(held, _)| held == declared_in) { + continue; + } + if let Some(text) = ws.text_of(declared_in) { + sources.push((declared_in.to_path_buf(), text)); + } + } + sources +} + +/// The edit for one offered action, computed now that the user has picked it. +/// +/// Today's eager answer at the offer's own position, narrowed to the action +/// whose title the client is holding. An action already carrying its edit is +/// returned untouched — a client may resolve anything it likes, and the quick +/// fixes in `code_action.rs` are complete when they are offered. +pub fn resolve(ws: &Workspace, action: CodeAction) -> Result { + if action.edit.is_some() { + return Ok(action); + } + let offer: Offer = action + .data + .clone() + .and_then(|data| serde_json::from_value(data).ok()) + .ok_or_else(|| NOT_OURS.to_string())?; + // A `codeAction/resolve` carries a `CodeAction`, not a `textDocument`, so + // the large-file fast path's gate (which reads the URI out of the params) + // never sees this request. A buffer that has grown past the threshold + // since it was offered an action is refused here instead: the fast path's + // whole contract is that a large buffer is never parsed, and one stale + // lightbulb is not a reason to break it. + let doc = ws.document(&offer.uri).filter(|doc| !doc.large).ok_or_else(|| GONE.to_string())?; + let offset = doc.positions().offset(offer.position); + code_actions(ws, &offer.uri, offset) + .into_iter() + .find_map(|offered| match offered { + CodeActionOrCommand::CodeAction(found) if key(&found.title) == key(&offer.title) => { + Some(found) + } + _ => None, + }) + .map(|mut resolved| { + resolved.data = action.data; + resolved + }) + .ok_or_else(|| GONE.to_string()) +} + +/// An action's identity: its title without the count phrase the offer and the +/// eager path can honestly disagree about. +/// +/// `"lucisv: remove port `rst` (updates 3 instantiations)"` keys as +/// ``"lucisv: remove port `rst`"``; a title with no such suffix +/// (`"lucisv: connect 1 missing port"`, whose count is the cursor's own file's +/// and therefore exact) keys as itself. An escaped identifier cannot contain a +/// space, so `" ("` never occurs inside a port name. +fn key(title: &str) -> &str { + title.strip_suffix(')').and_then(|head| head.rsplit_once(" (")).map_or(title, |(head, _)| head) +} + +/// An offered title with the workspace's own instantiation count in it, +/// replacing the one the offer's one or two files could see. +fn counted(ws: &Workspace, title: String, modules: &[String]) -> String { + let Some(head) = title.strip_suffix(')').and_then(|head| head.rsplit_once(" (")) else { + return title; + }; + let sites = modules.iter().map(|name| instances_of(ws, name)).sum(); + format!("{} ({})", head.0, vlog_refactor::sites_phrase(sites)) +} + +/// Every instance of `name` the index has seen. An edge is one written +/// statement, so its instances are counted rather than the edges themselves — +/// `sub u1 (), u2 ();` is two connection lists to rewrite and the title says +/// two. +fn instances_of(ws: &Workspace, name: &str) -> usize { + ws.index().instantiations_of(name).iter().map(|edge| edge.instances.len()).sum() +} + +/// Whether the index holds more than one declaration of `name` a module +/// reference could mean — the ambiguity `vlog_refactor::module_definition` +/// refuses to guess between, and the one the engine refuses a refactoring +/// over. +fn declared_twice(ws: &Workspace, name: &str) -> bool { + ws.index().units(name).iter().filter(|def| def.kind.is_instantiable()).count() > 1 +} + /// Run one of the three commands, or say why it cannot run. /// /// The answer is the `WorkspaceEdit` to apply plus the engine's warnings. How @@ -809,6 +1000,322 @@ mod tests { assert_eq!(edits_for(action.edit.as_ref().expect("edit"), &new_uri).len(), 2); } + // ------------------------------------------------------------------ + // the lazy offer and its resolve (TODO §37.1) + // ------------------------------------------------------------------ + + /// The offer a client that can resolve receives at `offset`. + fn offered(ws: &Workspace, uri: &Uri, offset: u32) -> Vec { + let position = ws.document(uri).expect("an open document").positions().position(offset); + offers(ws, uri, position, offset) + } + + /// One action's title and kind — what a lightbulb draws, and all an offer + /// promises. + fn menu(actions: &[CodeActionOrCommand]) -> Vec<(String, Option)> { + actions + .iter() + .map(|action| { + let CodeActionOrCommand::CodeAction(action) = action else { + return ("a command".to_string(), None); + }; + (action.title.clone(), action.kind.as_ref().map(|k| k.as_str().to_string())) + }) + .collect() + } + + /// The one action an offer holds. + fn only(actions: &[CodeActionOrCommand]) -> &CodeAction { + let [CodeActionOrCommand::CodeAction(action)] = actions else { + panic!("exactly one action, got {actions:#?}") + }; + action + } + + #[test] + fn the_lazy_offer_names_exactly_what_the_eager_one_names() { + let tree = Tree::new("lazy_menu"); + let mut ws = crowded(&tree, 40); + let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri"); + ws.set_document(sub_uri.clone(), SUB.to_string()); + let offset = SUB.find("input logic rst").expect("rst") as u32 + 12; + + let lazy = offered(&ws, &sub_uri, offset); + assert_eq!(menu(&lazy), menu(&code_actions(&ws, &sub_uri, offset))); + assert_eq!( + menu(&lazy)[0].0, + "lucisv: remove port `rst` (updates 3 instantiations)", + "counted from the index, and it agrees with the plan's own count" + ); + let action = only(&lazy); + assert!(action.edit.is_none(), "an offer carries no edit"); + assert!(action.data.is_some(), "it carries what resolve needs instead"); + } + + #[test] + fn the_offer_reads_the_buffer_and_at_most_the_declaring_file() { + // The pin `the_files_a_code_action_reads_are_the_modules_own_fan_out` + // is to the eager path; this is the same question asked of the offer, + // through the set it hands the engine. Neither the 40 noise files nor + // — and this is the point — any of the three instantiating tops. + let tree = Tree::new("lazy_reads"); + let mut ws = crowded(&tree, 40); + let sub = tree.path.join("sub.sv"); + let sub_uri = path_to_uri(&sub).expect("uri"); + ws.set_document(sub_uri.clone(), SUB.to_string()); + assert_eq!(ws.sources().len(), 44, "the whole workspace"); + assert_eq!(ws.module_sources(&sub, &["sub".to_string()]).len(), 4, "the eager fan-out"); + + // A cursor on a port declaration: the module is the buffer's own. + let read = offer_sources(&ws, &sub, SUB, &["sub".to_string()]); + let names: Vec = read + .iter() + .map(|(path, _)| path.file_name().expect("name").to_string_lossy().to_string()) + .collect(); + assert_eq!(names, ["sub.sv"], "one file, and it is the buffer itself"); + + // A cursor on an instantiation: the buffer, plus the one file the + // index says declares the module. + let top = tree.path.join("top0.sv"); + let top_text = std::fs::read_to_string(&top).expect("read"); + let read = offer_sources(&ws, &top, &top_text, &["sub".to_string()]); + let mut names: Vec = read + .iter() + .map(|(path, _)| path.file_name().expect("name").to_string_lossy().to_string()) + .collect(); + names.sort(); + assert_eq!(names, ["sub.sv", "top0.sv"], "and never top1, top2 or a noise file"); + } + + #[test] + fn a_resolved_action_carries_the_eager_edit_at_a_port_declaration() { + let tree = Tree::new("resolve_port"); + let mut ws = crowded(&tree, 40); + let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri"); + ws.set_document(sub_uri.clone(), SUB.to_string()); + let offset = SUB.find("input logic rst").expect("rst") as u32 + 12; + + let resolved = resolve(&ws, only(&offered(&ws, &sub_uri, offset)).clone()).expect("edit"); + let eager = only(&code_actions(&ws, &sub_uri, offset)).clone(); + assert_eq!(resolved.title, eager.title); + assert_eq!(resolved.kind, eager.kind); + assert_eq!(resolved.edit, eager.edit, "the same WorkspaceEdit, to the byte"); + assert!(resolved.data.is_some(), "the offer's own data survives the round trip"); + } + + #[test] + fn a_resolved_action_carries_the_eager_edit_at_an_instantiation() { + // The other cursor shape: an instantiation missing a connection, where + // the offer has to read the *instantiated* module's declaration to + // know there is anything to offer at all. + let tree = Tree::new("resolve_inst"); + let text = "module top;\n logic clk, rst;\n sub u_sub (.clk(clk));\nendmodule\n"; + tree.write("sub.sv", SUB); + let top = tree.write("top.sv", text); + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![tree.path.clone()]); + let uri = path_to_uri(&top).expect("uri"); + ws.set_document(uri.clone(), text.to_string()); + let offset = text.find("sub u_sub").expect("the instantiation") as u32; + + let lazy = offered(&ws, &uri, offset); + assert_eq!(menu(&lazy), menu(&code_actions(&ws, &uri, offset))); + assert_eq!(menu(&lazy)[0].0, "lucisv: connect 1 missing port"); + assert!(only(&lazy).edit.is_none()); + + let resolved = resolve(&ws, only(&lazy).clone()).expect("edit"); + assert_eq!(resolved.edit, only(&code_actions(&ws, &uri, offset)).edit); + assert_eq!( + edits_for(resolved.edit.as_ref().expect("edit"), &uri)[0].new_text, + ", .rst(rst)" + ); + } + + #[test] + fn the_resolved_edit_sees_an_unsaved_buffer_the_offer_could_not_count() { + // The pin `an_unsaved_buffer_contributes_the_instantiation_the_index + // _has_not_seen` moved to the lazy path. The offer counts instances + // from the index, which has not seen the unsaved one, so the title + // says three; the *edit* is computed over the fan-out plus every open + // buffer, so it disconnects all four. Exactness lives in the edit, + // which is what the user actually applies. + let tree = Tree::new("lazy_unsaved"); + let mut ws = crowded(&tree, 20); + let extra = tree.path.join("noise0.sv"); + let extra_uri = path_to_uri(&extra).expect("uri"); + let typed = "module noise0;\n logic c, r;\n sub u_new (.clk(c), .rst(r));\nendmodule\n"; + ws.set_document(extra_uri.clone(), typed.to_string()); + let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri"); + ws.set_document(sub_uri.clone(), SUB.to_string()); + let offset = SUB.find("input logic rst").expect("rst") as u32 + 12; + + let lazy = offered(&ws, &sub_uri, offset); + assert_eq!( + menu(&lazy)[0].0, + "lucisv: remove port `rst` (updates 3 instantiations)", + "the index has not seen the fourth" + ); + let resolved = resolve(&ws, only(&lazy).clone()).expect("edit"); + assert_eq!( + resolved.title, "lucisv: remove port `rst` (updates 4 instantiations)", + "and the resolve says so" + ); + let edit = resolved.edit.as_ref().expect("an edit"); + assert_eq!(edits_for(edit, &extra_uri).len(), 2, "the unsaved buffer is disconnected too"); + assert_eq!(resolved.edit, only(&code_actions(&ws, &sub_uri, offset)).edit); + } + + #[test] + fn a_resolve_of_an_action_the_buffer_no_longer_carries_is_refused() { + let tree = Tree::new("lazy_stale"); + let mut ws = crowded(&tree, 10); + let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri"); + ws.set_document(sub_uri.clone(), SUB.to_string()); + let offset = SUB.find("input logic rst").expect("rst") as u32 + 12; + let offered = only(&offered(&ws, &sub_uri, offset)).clone(); + + // The user kept typing: the port the lightbulb was about is gone. + ws.set_document(sub_uri.clone(), "module sub (\n input logic clk\n);\nendmodule\n".into()); + let message = resolve(&ws, offered.clone()).expect_err("nothing to resolve"); + assert_eq!(message, GONE); + + // And a document that has been closed altogether says the same. + ws.close_document(&sub_uri); + assert_eq!(resolve(&ws, offered).expect_err("no buffer"), GONE); + } + + #[test] + fn a_resolve_against_a_buffer_on_the_large_file_fast_path_is_refused() { + // `codeAction/resolve`'s params are a `CodeAction`, so the fast path's + // own gate — which reads a `textDocument` out of the params — never + // sees this request. A buffer that grew past the threshold since it + // was offered an action must still not be parsed. + let tree = Tree::new("lazy_large"); + let mut ws = crowded(&tree, 5); + let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri"); + ws.set_document(sub_uri.clone(), SUB.to_string()); + let offset = SUB.find("input logic rst").expect("rst") as u32 + 12; + let offered = only(&offered(&ws, &sub_uri, offset)).clone(); + + let _ = ws.set_client_settings(crate::settings::ClientSettings { + large_file_threshold: 8, + ..Default::default() + }); + ws.set_document(sub_uri.clone(), SUB.to_string()); + assert!(ws.document(&sub_uri).expect("open").large, "the buffer is on the fast path"); + assert_eq!(resolve(&ws, offered).expect_err("not parsed"), GONE); + } + + #[test] + fn a_resolve_of_something_this_server_never_offered_says_so() { + let tree = Tree::new("lazy_foreign"); + let (ws, uri, _) = opened(&tree); + let bare = CodeAction { title: "someone else's action".to_string(), ..Default::default() }; + assert_eq!(resolve(&ws, bare.clone()).expect_err("no data"), NOT_OURS); + + // Data that is not ours either — a shape `serde` cannot read as an + // offer. Refused, not guessed at. + let junk = CodeAction { data: Some(serde_json::json!({"nope": 1})), ..bare.clone() }; + assert_eq!(resolve(&ws, junk).expect_err("junk data"), NOT_OURS); + + // An action that already carries its edit — every quick fix in + // `code_action.rs`, and the port actions a non-resolving client is + // sent — comes straight back, because there is nothing to add to it. + let complete = + CodeAction { edit: Some(WorkspaceEdit::new(HashMap::from([(uri, vec![])]))), ..bare }; + assert_eq!(resolve(&ws, complete.clone()).expect("nothing to do"), complete); + } + + #[test] + fn a_name_the_workspace_declares_twice_is_not_offered_either() { + // The eager path refuses because both declaring files are in the set + // it reads (`a_module_declared_twice_is_refused_through_the_subset_as + // _well`). The offer reads neither, so it asks the index the same + // question — otherwise it would offer an action resolve then refuses. + let tree = Tree::new("lazy_ambiguous"); + let mut ws = crowded(&tree, 10); + tree.write("clone.sv", SUB); + ws.rebuild_index(); + let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri"); + ws.set_document(sub_uri.clone(), SUB.to_string()); + let offset = SUB.find("input logic rst").expect("rst") as u32 + 12; + + assert!(offered(&ws, &sub_uri, offset).is_empty()); + assert!(code_actions(&ws, &sub_uri, offset).is_empty(), "as the eager path does"); + } + + #[test] + fn a_title_keys_on_everything_but_its_count() { + assert_eq!( + key("lucisv: remove port `rst` (updates 3 instantiations)"), + key("lucisv: remove port `rst` (no instantiation in scope)") + ); + assert_eq!(key("lucisv: connect 1 missing port"), "lucisv: connect 1 missing port"); + assert_ne!( + key("lucisv: remove port `rst` (updates 1 instantiation)"), + key("lucisv: remove port `clk` (updates 1 instantiation)") + ); + } + + /// `cargo test --release -p lucisv_server --bin lucisv-server ports::tests::the_offer_is_flat -- --ignored --nocapture --test-threads=1` + #[test] + #[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"] + fn the_offer_is_flat_where_the_eager_answer_grows() { + // `performance_take2.md` §6a measured the eager answer growing with + // the module's fan-out — ~1.4 ms per instantiating file plus a ~13 ms + // floor, 185 ms at 128 files, to offer *zero* actions. The offer reads + // one file (a cursor on a port declaration) or two (a cursor on an + // instantiation), so its column should be flat. Beside the code it + // measures rather than in `perf.rs`, which is what `perf::mean` is + // `pub(crate)` for. + for instantiators in [3usize, 40, 128] { + let tree = Tree::new(&format!("perf_offer_{instantiators}")); + tree.write("sub.sv", SUB); + for n in 0..instantiators { + tree.write( + &format!("top{n:03}.sv"), + &format!( + "module top{n:03};\n logic c, r;\n \ + sub u_sub (.clk(c), .rst(r));\nendmodule\n" + ), + ); + } + for n in 0..200 { + tree.write( + &format!("noise{n:03}.sv"), + &format!( + "module noise{n:03};\n logic a;\n wire b;\n \ + assign b = a;\nendmodule\n" + ), + ); + } + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![tree.path.clone()]); + + for (what, file, needle, skip) in [ + ("a port declaration", "sub.sv", "input logic rst", 12u32), + ("an instantiation ", "top000.sv", "sub u_sub", 0), + ] { + let path = tree.path.join(file); + let text = std::fs::read_to_string(&path).expect("read"); + let uri = path_to_uri(&path).expect("uri"); + ws.set_document(uri.clone(), text.clone()); + let offset = text.find(needle).expect("the cursor") as u32 + skip; + let eager = crate::perf::mean(5, || { + std::hint::black_box(code_actions(&ws, &uri, offset)); + }); + let offer = crate::perf::mean(20, || { + std::hint::black_box(offered(&ws, &uri, offset)); + }); + eprintln!( + " fan-out {instantiators:>3}, cursor on {what}: eager {eager:?}, \ + offer {offer:?} ({} actions)", + offered(&ws, &uri, offset).len() + ); + } + } + } + #[test] fn an_unknown_command_is_declined() { let tree = Tree::new("unknown"); diff --git a/crates/lucisv_server/src/server/dispatch.rs b/crates/lucisv_server/src/server/dispatch.rs index 0042d91..ff91c82 100644 --- a/crates/lucisv_server/src/server/dispatch.rs +++ b/crates/lucisv_server/src/server/dispatch.rs @@ -14,22 +14,22 @@ use lsp_server::{Request, RequestId, Response}; use lsp_types::request::{ CallHierarchyIncomingCalls, CallHierarchyOutgoingCalls, CallHierarchyPrepare, - CodeActionRequest, CodeLensRequest, Completion, DocumentDiagnosticRequest, - DocumentHighlightRequest, DocumentLinkRequest, DocumentSymbolRequest, ExecuteCommand, - FoldingRangeRequest, Formatting, GotoDefinition, GotoTypeDefinition, GotoTypeDefinitionParams, - GotoTypeDefinitionResponse, HoverRequest, InlayHintRequest, InlineCompletionRequest, - LinkedEditingRange, OnTypeFormatting, PrepareRenameRequest, RangeFormatting, References, - Rename, Request as _, SelectionRangeRequest, SemanticTokensFullDeltaRequest, - SemanticTokensFullRequest, SemanticTokensRangeRequest, SignatureHelpRequest, - TypeHierarchyPrepare, TypeHierarchySubtypes, TypeHierarchySupertypes, WillRenameFiles, - WillSaveWaitUntil, WorkspaceDiagnosticRequest, WorkspaceSymbolRequest, + CodeActionRequest, CodeActionResolveRequest, CodeLensRequest, Completion, + DocumentDiagnosticRequest, DocumentHighlightRequest, DocumentLinkRequest, + DocumentSymbolRequest, ExecuteCommand, FoldingRangeRequest, Formatting, GotoDefinition, + GotoTypeDefinition, GotoTypeDefinitionParams, GotoTypeDefinitionResponse, HoverRequest, + InlayHintRequest, InlineCompletionRequest, LinkedEditingRange, OnTypeFormatting, + PrepareRenameRequest, RangeFormatting, References, Rename, Request as _, SelectionRangeRequest, + SemanticTokensFullDeltaRequest, SemanticTokensFullRequest, SemanticTokensRangeRequest, + SignatureHelpRequest, TypeHierarchyPrepare, TypeHierarchySubtypes, TypeHierarchySupertypes, + WillRenameFiles, WillSaveWaitUntil, WorkspaceDiagnosticRequest, WorkspaceSymbolRequest, }; use lsp_types::{ CallHierarchyIncomingCallsParams, CallHierarchyOutgoingCallsParams, CallHierarchyPrepareParams, - CodeActionKind, CodeActionParams, CodeLensParams, CompletionParams, DocumentDiagnosticParams, - DocumentDiagnosticReportResult, DocumentHighlightParams, DocumentLinkParams, - DocumentSymbolParams, DocumentSymbolResponse, ExecuteCommandParams, FoldingRangeParams, - GotoDefinitionParams, GotoDefinitionResponse, HoverParams, InlayHintParams, + CodeAction, CodeActionKind, CodeActionParams, CodeLensParams, CompletionParams, + DocumentDiagnosticParams, DocumentDiagnosticReportResult, DocumentHighlightParams, + DocumentLinkParams, DocumentSymbolParams, DocumentSymbolResponse, ExecuteCommandParams, + FoldingRangeParams, GotoDefinitionParams, GotoDefinitionResponse, HoverParams, InlayHintParams, InlineCompletionParams, LinkedEditingRangeParams, Position, ReferenceParams, RenameFilesParams, RenameParams, SelectionRangeParams, SemanticTokens, SemanticTokensDeltaParams, SemanticTokensParams, SemanticTokensRangeParams, SemanticTokensRangeResult, @@ -258,10 +258,26 @@ impl Server { if code_action::wanted(only.as_deref(), &CodeActionKind::new(ports::REFACTOR_PORTS)) { let offset = doc.positions().offset(p.range.start); - actions.extend(ports::code_actions(&self.workspace, &uri, offset)); + // A client that can resolve is offered the actions without + // their edits, which is what keeps a cursor resting on an + // instantiation off the module's fan-out; one that cannot + // gets the whole edit, exactly as before. + actions.extend(match self.abilities.code_action_resolve { + true => ports::offers(&self.workspace, &uri, p.range.start, offset), + false => ports::code_actions(&self.workspace, &uri, offset), + }); } to_value(actions) }), + // The edit for an action offered without one. An action that + // already carries its edit comes straight back, so a client that + // resolves everything it is offered is answered too. + CodeActionResolveRequest::METHOD => decode(request).and_then(|action: CodeAction| { + match ports::resolve(&self.workspace, action) { + Ok(resolved) => to_value(resolved), + Err(message) => Err(Failure::Request(message)), + } + }), // Custom method, so it is matched by name rather than through a // `lsp_types::request` type. Nothing advertises it: a client that // does not know it never asks. diff --git a/crates/lucisv_server/src/server/mod.rs b/crates/lucisv_server/src/server/mod.rs index cb42616..789c421 100644 --- a/crates/lucisv_server/src/server/mod.rs +++ b/crates/lucisv_server/src/server/mod.rs @@ -104,6 +104,13 @@ pub struct ClientAbilities { /// Whether the client hosts the custom lucisv hierarchy sidebar and wants /// a notification whenever the installed workspace index changes. pub hierarchy_view: bool, + /// Whether the client can fetch a code action's `edit` through + /// `codeAction/resolve` — `textDocument.codeAction.resolveSupport` + /// listing `"edit"`. Only then are the port refactorings *offered* without + /// their edits; a client that said nothing gets the whole edit up front, + /// which is what every client got before this was read + /// (`docs/features/lazy-code-action/README.md`). + pub code_action_resolve: bool, } /// Everything the server owns. diff --git a/crates/lucisv_server/src/state.rs b/crates/lucisv_server/src/state.rs index acaafc5..4bb5a8f 100644 --- a/crates/lucisv_server/src/state.rs +++ b/crates/lucisv_server/src/state.rs @@ -1797,6 +1797,17 @@ impl Workspace { Some(view) } + /// The files the view cache is holding, newest first. + /// + /// Test-only, and it exists for one question: whether an answer read a + /// file at all. A `Location` computed from the index alone must leave this + /// empty, which is the whole point of `locate::definition_location` — see + /// `docs/features/lazy-code-action/README.md`. + #[cfg(test)] + pub(crate) fn held_views(&self) -> Vec { + self.views.borrow().iter().map(|view| view.path.clone()).collect() + } + /// The held view for `path`, moved to the front so the bounds below drop /// whatever has gone longest unused. fn cached_view(&self, path: &Path) -> Option> { diff --git a/crates/lucisv_server/src/symbols.rs b/crates/lucisv_server/src/symbols.rs index a6fe0eb..14fe859 100644 --- a/crates/lucisv_server/src/symbols.rs +++ b/crates/lucisv_server/src/symbols.rs @@ -4,7 +4,7 @@ use lsp_types::{Location, SymbolInformation, SymbolKind as LspKind}; use vlog_semantic::{Symbol, SymbolKind}; -use crate::locate::location; +use crate::locate::definition_location; use crate::state::{Document, Workspace, WORKSPACE_SYMBOL_LIMIT}; /// How a declaration reads in hover text. @@ -129,7 +129,11 @@ pub fn workspace_symbols(ws: &Workspace, query: &str) -> Vec .take(WORKSPACE_SYMBOL_LIMIT) .filter_map(|hit| { let path = index.path(hit.def.file)?; - let location: Location = location(ws, path, hit.def.name_span)?; + // A unit's range is in the index; a member's is not, and falls + // back to the file read. `workspace/symbol` answers up to + // `WORKSPACE_SYMBOL_LIMIT` hits at once, so this is the request + // the index-carried positions matter most to. + let location: Location = definition_location(ws, path, hit.def)?; // `deprecated` is a deprecated protocol field that is still a // named field of the struct. #[allow(deprecated)] diff --git a/crates/lucisv_server/tests/e2e.rs b/crates/lucisv_server/tests/e2e.rs index 2fb946f..70b8fe1 100644 --- a/crates/lucisv_server/tests/e2e.rs +++ b/crates/lucisv_server/tests/e2e.rs @@ -1484,6 +1484,106 @@ fn a_port_code_action_and_the_port_commands_round_trip_over_the_wire() { ); assert!(conditional["result"].is_null(), "a refusal carries no edits: {conditional:#?}"); + // 7. The client above sent `"capabilities":{}`, so every action came back + // complete — which is the whole of the no-resolveSupport contract. + assert!(port_action["data"].is_null(), "nothing to resolve for this client: {port_action:#?}"); + + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_client_that_resolves_is_offered_the_port_action_without_its_edit() { + // The lazy half of the same feature (TODO §37.1): a client that declares + // `codeAction.resolveSupport.properties: ["edit"]` is offered the action + // with `data` and no `edit`, and gets the edit from `codeAction/resolve`. + // Only an e2e test can check that the `data` really survives the round + // trip through the client — it is opaque JSON the server never sees again + // until the client hands it back. + let dir = temp_dir("resolve"); + let sub = dir.join("sub.sv"); + std::fs::write(&sub, PORTS_SUB).expect("write"); + let top = dir.join("top.sv"); + std::fs::write(&top, PORTS_TOP).expect("write"); + let root = format!("file://{}", dir.display()); + let top_uri = format!("file://{}", top.display()); + + let session = [ + frame(&format!( + r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{"textDocument":{{"codeAction":{{"resolveSupport":{{"properties":["edit"]}}}}}}}}}}}}"# + )), + frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), + frame(&format!( + r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{top_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, + serde_json::to_string(PORTS_TOP).expect("json") + )), + // The cursor on `u_sub`, whose instantiation is missing `.rst`. + frame(&format!( + r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/codeAction","params":{{"textDocument":{{"uri":"{top_uri}"}},"range":{{"start":{{"line":2,"character":6}},"end":{{"line":2,"character":6}}}},"context":{{"diagnostics":[]}}}}}}"# + )), + frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), + frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), + ] + .concat(); + let messages = talk(&session); + + // 1. The capability says a resolve is answered. + let initialize = messages.iter().find(|m| m["id"] == 1).expect("initialize response"); + let provider = &initialize["result"]["capabilities"]["codeActionProvider"]; + assert_eq!(provider["resolveProvider"], true, "{provider:#?}"); + + // 2. The offer carries `data` and no `edit`. + let actions = messages.iter().find(|m| m["id"] == 2).expect("codeAction response"); + let offered = actions["result"].as_array().expect("an array of actions"); + let action = offered + .iter() + .find(|a| a["kind"] == "refactor.rewrite.lucisv.ports") + .unwrap_or_else(|| panic!("no port action in {offered:#?}")); + assert_eq!(action["title"], "lucisv: connect 1 missing port"); + assert!(action["edit"].is_null(), "an offer carries no edit: {action:#?}"); + assert_eq!(action["data"]["uri"], top_uri.as_str()); + assert_eq!(action["data"]["title"], action["title"]); + + // 3. Handing that same action back gets the edit. A second session, + // because the action has to be echoed verbatim and it is only known now. + let resolve = [ + frame(&format!( + r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{"textDocument":{{"codeAction":{{"resolveSupport":{{"properties":["edit"]}}}}}}}}}}}}"# + )), + frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), + frame(&format!( + r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{top_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, + serde_json::to_string(PORTS_TOP).expect("json") + )), + frame(&format!( + r#"{{"jsonrpc":"2.0","id":3,"method":"codeAction/resolve","params":{}}}"#, + serde_json::to_string(action).expect("json") + )), + // ...and an action this server never offered is refused with a + // sentence rather than an empty edit. + frame( + r#"{"jsonrpc":"2.0","id":4,"method":"codeAction/resolve","params":{"title":"someone else's action"}}"#, + ), + frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), + frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), + ] + .concat(); + let messages = talk(&resolve); + let resolved = messages.iter().find(|m| m["id"] == 3).expect("resolve response"); + let edits = resolved["result"]["edit"]["changes"][&top_uri] + .as_array() + .unwrap_or_else(|| panic!("no edit in {resolved:#?}")); + assert_eq!(edits.len(), 1); + assert_eq!(edits[0]["newText"], ", .rst(rst)"); + assert_eq!(edits[0]["range"]["start"]["line"], 2); + assert_eq!(resolved["result"]["title"], "lucisv: connect 1 missing port"); + + let foreign = messages.iter().find(|m| m["id"] == 4).expect("refusal response"); + assert_eq!(foreign["error"]["code"], -32803, "LSP's RequestFailed"); + assert!( + foreign["error"]["message"].as_str().is_some_and(|m| m.contains("no lucisv port")), + "{foreign:#?}" + ); + let _ = std::fs::remove_dir_all(&dir); } diff --git a/crates/vlog_refactor/src/lib.rs b/crates/vlog_refactor/src/lib.rs index ba009ef..cf65a42 100644 --- a/crates/vlog_refactor/src/lib.rs +++ b/crates/vlog_refactor/src/lib.rs @@ -42,7 +42,7 @@ pub use instantiate::{ }; pub use ports::{ add_port, enclosing_module, may_have_port_action, port_action_modules, port_actions, - propagate_ports, remove_port, ModuleRef, PortAction, + propagate_ports, remove_port, sites_phrase, ModuleRef, PortAction, }; pub use rename::{ contains_word, prepare_rename, prepare_rename_here, rename, rename_name_at, RenameTarget, diff --git a/crates/vlog_refactor/src/ports/mod.rs b/crates/vlog_refactor/src/ports/mod.rs index e8bba87..66627a1 100644 --- a/crates/vlog_refactor/src/ports/mod.rs +++ b/crates/vlog_refactor/src/ports/mod.rs @@ -236,7 +236,12 @@ pub fn enclosing_module(text: &str, offset: u32) -> Option { /// "updates 3 instantiations" / "updates 1 instantiation" / "no instantiation /// in scope". -fn sites_phrase(sites: usize) -> String { +/// +/// Public because a server may have to write the same sentence with a count of +/// its own: an offer that has not read the fan-out takes the number from its +/// workspace index instead of from the plan, and the two must not come to be +/// worded differently (`docs/features/lazy-code-action/README.md`). +pub fn sites_phrase(sites: usize) -> String { match sites { 0 => "no instantiation in scope".to_string(), 1 => "updates 1 instantiation".to_string(), diff --git a/docs/features/lazy-code-action/README.md b/docs/features/lazy-code-action/README.md new file mode 100644 index 0000000..27fcdc0 --- /dev/null +++ b/docs/features/lazy-code-action/README.md @@ -0,0 +1,573 @@ +# lazy-code-action + +TODO §37 — the three server residues left over from §10: the lazy +`codeAction/resolve` for the port refactorings (§37.1), the `inlayHint` zero at +the default scope (§37.2), and `locate::location` onto `DeclPositions` +(§37.3). One README, one section each. + +## Goal + +**§37.1.** `textDocument/codeAction` arrives on nearly every cursor move, and +the port refactorings answered it by computing the *whole* edit — over the +instantiated module's entire fan-out plus every open buffer, each file read as +text. `docs/performance_take2.md` §6a measured what that costs on opentitan: +~1.4 ms per instantiating file plus a ~13 ms floor, **185–201 ms at a 128-file +fan-out, to offer zero actions**, above §3's "reads as a hang" line, on the hot +path. The *offer* is now local — the buffer, plus the instantiated module's own +declaration when the cursor is on an instantiation — and the edit is computed +by `codeAction/resolve` when the user picks the action. A client that cannot +resolve is unaffected: it still gets the edit up front. + +**§37.2.** `inlayHint` returns 0 hints at the default (folder) scope where the +workspace scope returns 4 (`performance_take2.md` §4b, §8.9), the one §4b row +the `didOpen` widen did not fix. Investigated, and it is **not a bug** — the +finding is written out below, with two tests that pin it. + +**§37.3.** Every file-scope declaration's client-side range is already in the +index (`DeclPositions`, added by the design-hierarchy round), so +`textDocument/definition` and `workspace/symbol` need not read a file to +convert an indexed span. They no longer do: **27.7 µs → 0.40 µs per +definition** on opentitan. + +## Assumptions + +- **The offer may be optimistic; the resolve is exact.** A refusal the engine + can only see over the fan-out — an instantiation elsewhere connecting `sub`'s + ports *by position*, which makes `remove_port` refuse whole — is invisible to + a one-file offer, so the lightbulb can appear and the resolve then decline + with "the action is no longer available". This is the trade LSP's resolve + model is for; the alternative is the 185 ms. The refusals cheap enough to + keep are kept: a module the index declares twice is checked through + `WorkspaceIndex::units` before anything is offered, exactly as the eager path + refuses over the two declaring files it reads. +- **The count in an offered title comes from the index and may be one behind.** + `instantiations_of(name)` records one edge per *written statement* with its + instances, and the title counts **instances** (`sub u1(), u2();` is two), to + match what the eager title counts — the instances the plan really rewrites. + The two disagree exactly where the index cannot know: an unsaved buffer's new + instantiation, a file-scope instantiation site (which records no edge at + all), an instance connecting with `.*`. So the offered and resolved actions + are matched on the title *without* its count phrase (`ports::key`), and the + resolved action carries the exact title. +- **`Def::lines.positions` is `Some` for every file-scope declaration and + `None` for every member**, as `DeclLines` documents. §37.3 relies on that: + members keep the file-read path, which is not a fallback nobody takes — it is + the only answer a port has. +- **`codeAction/resolve` carries no `textDocument`**, so the large-file fast + path's gate — which reads a URI out of the params — never sees it. `resolve` + refuses a buffer on that fast path itself: the mode's contract is that a + large buffer is never parsed, and one stale lightbulb is not a reason to + break it. +- An **open buffer** keeps the file-read path in §37.3 whatever the index + recorded, because the buffer's text may have moved since it was indexed and + every other answer about that buffer is computed against the text it holds + now. + +## Handshakes + +- **`vlog_refactor` → server.** `ports::sites_phrase` is now `pub` (re-exported + from the crate root as `vlog_refactor::sites_phrase`). The server writes the + same sentence with a count of its own, and one spelling of a user-visible + string is the point. Nothing else in `vlog_refactor` changed; `port_actions`, + `port_action_modules` and `module_definition` are consumed exactly as before. +- **`Workspace` → server.** `Workspace::held_views()` added, `#[cfg(test)]` + and `pub(crate)`: the view cache is how a test asserts that an answer read no + file. No production caller. +- **`main.rs` → `server`.** `ClientAbilities` gains `code_action_resolve`, read + at `initialize` from `textDocument.codeAction.resolveSupport.properties` + containing `"edit"`. The `initialize` result advertises + `codeActionProvider.resolveProvider: true` unconditionally — the server can + always answer a resolve, including for an action that already carries its + edit, which it hands straight back. +- **The wire.** New method answered: `codeAction/resolve`. New field on an + offered port action: `data` (`{uri, position, title}`), opaque to the client. + The quick fixes in `code_action.rs` are unchanged and still complete when + offered. + +## Status / TODO + +- [x] §37.1 `ports::offers` — the local offer, titles counted from the index, + `data` instead of an edit. +- [x] §37.1 `ports::resolve` — today's eager answer at the offer's position, + matched on `key(title)`; `RequestFailed` with "the action is no longer + available." when nothing matches, and a distinct sentence for an action + this server never offered. +- [x] §37.1 capability gate: `code_action_resolve_support` in `main.rs`, + `ClientAbilities::code_action_resolve`, the dispatch branch. +- [x] §37.1 `resolve_provider: Some(true)` advertised; `codeAction/resolve` + dispatch arm. +- [x] §37.1 tests: the offer's menu equals the eager one over `crowded(40)`; + the offer's source set is the buffer (+ the declaring file); the resolved + edit is byte-equal to the eager one at both cursor shapes; the unsaved + buffer answered by the resolve; a stale and a closed document refused; a + foreign action refused; a complete action returned untouched; the + duplicate-declaration refusal; a buffer that grew onto the large-file + fast path; `key`'s own unit test. +- [x] §37.1 e2e over the wire, both client shapes. +- [x] §37.1 perf: the "offer" column on `perf.rs`'s + `a_code_action_at_an_instantiation_before_and_after`, plus + `ports::tests::the_offer_is_flat_where_the_eager_answer_grows` + (3/40/128 instantiators, both cursor shapes). +- [x] §37.2 investigated; finding written below; two tests at the default + scope. +- [x] §37.3 `locate::definition_location`, routed through `nav::definition` + and `symbols::workspace_symbols`. +- [x] §37.3 pins: the encoding shapes, no `file_view` created, members keep + the read, the open-buffer case. +- [x] §37.3 opentitan timing, read-only + (`locate::tests::defining_over_a_real_project`). +- [ ] Not done, deliberately: **memoising `module_sources`** per (module, index + generation), take 1's other suggestion. The offer makes it unnecessary on + the hot path — the fan-out is now read once per *click* — and a cache + keyed on a generation is a staleness question this round did not need to + open. +- [ ] Not done, deliberately: **the quick fixes stay eager.** They are built + from the buffer's own violations, which the server has already computed + for the diagnostics; there is nothing to defer. + +## §37.1 — how the offer stays local + +`ports::offers` runs the engine's own `port_actions` over a source set built by +`ports::offer_sources`: + +1. **the buffer the request names**, from the open document (no read); +2. **the declaring file of every module `port_action_modules` named**, via + `vlog_refactor::module_definition(index, name)` — the same two steps + `inlay.rs`'s `Plans::read` takes, and one file read at most. + +A cursor on a **port declaration** names its own module, whose declaring file +*is* the buffer, so that case reads nothing at all. A cursor on an +**instantiation** names the instantiated module, and its declaration is what +`propagate_ports` needs to know which connections are missing — so the offer +is exact for that action, including its "connect N missing ports" count, which +is a count of edits in the cursor's own file. + +The edits `port_actions` computes over those one or two files are thrown away. +Only the titles and the kind survive, plus `data`. + +`ports::resolve` re-runs `ports::code_actions` — today's eager path, unchanged +— at the offer's position and returns the action whose `key(title)` matches. + +### Measured + +This machine, 2026-09-04, release. + +`cargo test --release -p lucisv_server perf::a_code_action -- --ignored +--nocapture --test-threads=1` — the original probe (a port of a module +instantiated in 3 of 504 files, 200 lines each), now with the offer column +TODO §37.1 asked for: + +| whole workspace | fan-out (eager) | **offer** | `sources()` alone | +|---:|---:|---:|---:| +| 776 ms | 433 µs | **58 µs** | 11.5 ms | + +`cargo test --release -p lucisv_server --bin lucisv-server +ports::tests::the_offer_is_flat -- --ignored --nocapture --test-threads=1` — +200 noise modules plus `n` files instantiating `sub`, the shape §6a measured +on opentitan: + +| fan-out | cursor | eager | **offer** | actions | +|---:|---|---:|---:|---:| +| 3 | a port declaration | 485 µs | **68 µs** | 1 | +| 3 | an instantiation | 172 µs | **72 µs** | 0 | +| 40 | a port declaration | 4.84 ms | **53 µs** | 1 | +| 40 | an instantiation | 1.45 ms | **55 µs** | 0 | +| 128 | a port declaration | 15.0 ms | **53 µs** | 1 | +| 128 | an instantiation | 4.60 ms | **55 µs** | 0 | + +The eager column grows with the fan-out and the offer column does not: 53–72 µs +at every size, both cursors (the two 3-file rows are the first measurements +taken in the process and carry that much warm-up). The two "0 actions" rows are +§6a's own complaint — a cursor on a fully-connected instantiation, where the old +path spent its whole bill to offer nothing. + +## §37.2 — the `inlayHint` zero at the default scope is correct + +**Finding: not a bug. `performance_take2.md` §4b's last row compares a +different question from every row above it.** + +Every other row of that table asks about `aes` — `definition`, `hover`, +`signatureHelp`, `references` on the `aes` instantiation in +`hw/ip/aes/dv/tb/tb.sv`. `aes` is declared in `hw/ip/aes/rtl/aes.sv`, which the +`didOpen` widen reaches: opening `hw/ip/aes/dv/tb/tb.sv` at the shipped +`scopeDepth` of 2 raises to `hw/ip/aes`, 124 files. So those rows answer. + +`inlayHint` cannot ask about `aes` at all: that instantiation's connections are +**named** (`.clk_i(clk)`), and a named connection gets no hint by design — the +reader can already see which port is which. The only positional connections in +`tb.sv` are: + +```systemverilog +pins_if #($bits(lc_escalate)) lc_escalate_if (lc_escalate); +pins_if #(1) idle_if (idle); +``` + +Two positional parameter overrides and two positional port connections — **the +4 hints the workspace scope returns**. `pins_if` is declared in +`hw/dv/sv/common_ifs/pins_if.sv`; there is no `pins_if` anywhere under +`hw/ip/aes` (checked). So at the default scope the module is genuinely not in +the index, `vlog_refactor::module_definition` has nothing to answer with, and +`Plans::read` declines — which is the documented contract: an instantiation +whose module the index does not hold gets no hints, because guessing port names +puts a wrong name on screen with no way for the reader to tell. + +`inlay.rs` uses **the same lookup its neighbours use**. `signature.rs:28` and +`completion`'s module-header tier call `vlog_refactor::module_definition` on the +same index; hover and definition go through the same overlay. Asked about +`pins_if` at the default scope, every one of them answers nothing too. There is +no lookup inlay is missing. + +Two tests pin it (`inlay.rs`), on an opentitan-shaped tree — `ip/aes/rtl`, +`ip/aes/dv/tb`, and a `dv/common` beside the block: + +- `the_default_scope_hints_a_module_the_didopen_widen_reached` — at the + **default** scope (no `index.scope`, `scopeDepth` 2), the instantiation of the + block's own module is hinted. The default scope hints; §4b's row is not + evidence that it does not. +- `an_out_of_scope_module_is_unhinted_exactly_as_it_is_undefined` — the + instantiation of the module outside the block gets no hints, **and** + `textDocument/definition` and hover give nothing for it either; widening to + the workspace scope makes all three answer. + +For the lead: if the wanted behaviour is that a hint pulls its module's +declaration in from outside the scope, that is a *scope* change (the widen +would have to follow instantiation edges), and it would change what +`definition`, `hover` and `completion` answer at the same time. It is not an +inlay-hint fix, and it is not what this round did. + +## §37.3 — `locate::definition_location` + +`Def::lines.positions` holds `{name, decl}` as `Utf16Range`s, converted through +the declaring file's own `LineIndex::utf16_position` while it was indexed — +which is the very converter `convert::Positions` uses on the wire, so the two +cannot disagree. `locate::definition_location(ws, path, def)` returns the name's +range straight from there when the file has no open buffer, and falls through to +`locate::location`'s read otherwise (an open buffer, or a member, which records +no positions). + +Routed through: `nav::definition`'s `Definition::External` arm and +`symbols::workspace_symbols`. `nav`'s `` `define`` arm keeps the read — a +`DefineTable` entry is not a `Def` and has no recorded positions. + +### Pins + +- `locate::tests::the_two_paths_agree_over_multi_byte_astral_crlf_and_a_bom` — + one file with a BOM at offset 0, CRLF endings, two- and three-byte + characters and an astral character that is two UTF-16 code units; the + index-only `Location` equals the file-read one exactly. +- `locate::tests::a_file_scope_definition_is_located_without_reading_its_file` + and `nav::tests::a_cross_file_definition_reads_no_file` — asserted through + `Workspace::held_views()`, the view cache a read would land in. Empty after + the definition and after a `workspace/symbol`; one entry after the same + question is asked the old way. +- `locate::tests::a_member_keeps_the_file_read_path` — a port records no + positions and still answers, through the read. +- `locate::tests::an_open_buffer_still_answers_from_the_buffer`. + +### Measured, over opentitan, read-only + +`LUCISV_PERF_CORPUS=/Users/guoliangchen/repo/opentitan cargo test --release -p +lucisv_server --bin lucisv-server locate::tests::defining -- --ignored +--nocapture --test-threads=1`, 3 976 indexed files, 200 targets (modules the +corpus instantiates, each in a different file): + +| | total, 200 definitions | per definition | +|---|---:|---:| +| file-read (before) | 5.54 ms | 27.7 µs | +| index-only (after) | 80.5 µs | **0.40 µs** | + +69× on the conversion, and it is the whole of what a cross-file +`textDocument/definition` into a closed file was doing besides the lookup. +`git -C ~/repo/opentitan status --porcelain` unchanged after the run. + +## Work log + +### 2026-09-04 — dev agent (Opus) + +- Read `CLAUDE.md`, TODO §37 and the §10 lines it closes, + `docs/performance_take2.md` §4b/§6a/§7/§8, and the code each item names. +- **§37.3 first** (smallest, independent). `locate::definition_location` plus + `locate::range`; `state.rs` gained `held_views()` (`#[cfg(test)]`, + `pub(crate)`) so a test can assert that no file was read. Routed + `nav::definition` and `symbols::workspace_symbols` through it. Four tests in + `locate.rs` (new test module) and one in `nav.rs`. + - Deviation from the plan's expectation, recorded: the plan said "no + `file_view` created for a file-scope definition"; the assertion is through + `Workspace::held_views()`, a new test-only accessor, rather than a + counter — the cache *is* the counter, and it is already what `state.rs`'s + own tests assert against. + - One thing the plan did not anticipate: an **open buffer** must keep the + file-read path. Its `Def` spans are the disk file's until the next + re-index, and converting them against the buffer's current text is what + every other answer about that buffer does. Pinned by + `an_open_buffer_still_answers_from_the_buffer`, which asserts the + (pre-existing, unchanged) stale-span behaviour rather than pretending this + round fixed it. +- **§37.2 second.** Investigated by reading `hw/ip/aes/dv/tb/tb.sv` and + locating `pins_if` in the opentitan checkout (read-only, `find`/`ls` only). + The zero is correct; the finding is written above, with two tests. No + production code changed for this item. +- **§37.1 last.** `ports::offers`, `ports::offer_sources`, `ports::resolve`, + `ports::key`, `ports::counted`, `ports::instances_of`, + `ports::declared_twice`; `ClientAbilities::code_action_resolve`; + `code_action_resolve_support` in `main.rs`; `resolve_provider: Some(true)`; + the dispatch branch and the `codeAction/resolve` arm. + - **Deviation, flagged:** `vlog_refactor::ports::sites_phrase` was made + `pub` and re-exported. The plan allowed a change to + `crates/vlog_refactor/src/ports/mod.rs` "only if the offer needs a new + one-file question", and this is not one — it is the alternative to writing + a second spelling of a user-visible sentence in the server and letting the + two drift. No behaviour changed in `vlog_refactor`. + - **Deviation, flagged:** the plan said resolve returns "the action whose + title matches". Exact title matching cannot work, because the offer's + count comes from the index and the eager count from the plan, and the + plan's own §37.1 requires the unsaved-buffer case (index 3, plan 4) to + resolve. Matching is therefore on `key(title)` — the title with its + trailing ` (…)` count phrase removed. An escaped identifier cannot contain + a space, so `" ("` never occurs inside a port name; `a_title_keys_on_ + everything_but_its_count` pins it. + - **Deviation, flagged:** `resolve` returns an action that already carries an + `edit` unchanged instead of refusing it. A client that declares + `resolveSupport` may resolve anything it was offered, including the quick + fixes, and refusing those would break fix-on-save for exactly the clients + this feature is for. + - `resolve` refuses a large-file buffer, because the fast path's own gate + cannot see a request whose params are a `CodeAction`. Found by reading + `server/large_file.rs`'s `document_uri`, not by a test failing; pinned by + `a_resolve_against_a_buffer_on_the_large_file_fast_path_is_refused`. + - The existing eager pin `an_unsaved_buffer_contributes_the_instantiation_ + the_index_has_not_seen` was **kept** rather than moved: the eager path is + still live code for a client without `resolveSupport`. Its lazy sibling + `the_resolved_edit_sees_an_unsaved_buffer_the_offer_could_not_count` is the + moved pin. +- **The two new perf probes live beside the code they measure**, not in + `perf.rs`: `perf.rs` is already the one file over the size rule with a + written reason (895 production lines, `docs/features/decomposition-server`), + and `perf::mean` is `pub(crate)` precisely so a probe can sit next to its + subject — `nav.rs`'s references probes already do. `perf.rs` grew by the + five lines of the offer column and nothing else (900 lines). +- Files touched outside the plan's expected set: **none** + (`crates/vlog_refactor/src/lib.rs` for the re-export is the only file not + named in it; `crates/vlog_refactor/src/ports/mod.rs` was named). + +## Gates (dev, guarded, 2026-09-04) + +- `cargo fmt -p lucisv_server`, `cargo fmt -p vlog_refactor` — clean + (`--check` verified). +- `cargo clippy --all-targets` — clean, no new `#[allow]`. +- `tools/guard.sh -- cargo test --workspace` — **3 734 passed, 0 failed, + 44 ignored** (the ignored are the perf probes). +- `tools/guard.sh -- tools/corpus_check.sh` — **814/820 (99.3 %)**, the same + six failures, `verification-error: none`, `crash: none`. +- `cargo build --release -p lucisv_server` then `tools/guard.sh -- node + editors/vscode/smoke.js target/release/lucisv-server` — OK, 20 messages. +- No guard kill at any point. `git -C ~/repo/opentitan status --porcelain` + after every opentitan read: the same three pre-existing modifications + (`hw/ip/aes/dv/tb/tb.sv`, both `ast.sv`), nothing else. + +## QA log + +### 2026-09-04 — QA agent (Sonnet) + +Read `CLAUDE.md`, TODO §37, the dev's account above in full (Goal, Assumptions, +Handshakes, work log — all five flagged deviations), then the diffs of every +touched file. Attacked the three items over the real code, not just the +dev's own tests; every scratch test below was added as a temporary `#[test]`, +run, and removed before this log was written (`git diff --stat` after cleanup +is byte-identical to the dev's own: 15 modified + this README). + +**§37.1 — lazy `codeAction`/`resolve`.** + +- Malformed `data` (scratch test in `ports.rs`): a wrong-typed `uri` (a JSON + number) fails to deserialize into `Offer` → `NOT_OURS`; a well-formed `data` + naming a document **never opened at all** (distinct from one that was open + and closed) → `GONE`; a `position` far past EOF → `Positions::offset` clamps + to the text length (confirmed by reading `convert.rs:44-59`) rather than + panicking, `code_actions` at the clamped offset finds nothing, → `GONE`. No + panic in any case. +- A closed document and a document whose port has since been removed: both + already pinned by the dev's `a_resolve_of_an_action_the_buffer_no_longer_ + carries_is_refused`; reproduced by re-running it directly. +- The unsaved-buffer "different count" case (index says 3, buffer really has + 4): the dev's `the_resolved_edit_sees_an_unsaved_buffer_the_offer_could_not_ + see` is exactly this attack — re-run, still resolves with the corrected + title and the wider edit. +- A quick-fix action passed to `resolve`: `code_action.rs`'s `quick_fix` + (line ~76) always sets `edit: Some(...)`, so it always takes `resolve`'s + first branch (`action.edit.is_some()` → returned unchanged) regardless of + origin — confirmed by reading the function rather than by a redundant + integration test, since the logic path is identical to the dev's own + synthetic "complete" case in `a_resolve_of_something_this_server_never_ + offered_says_so`. +- Title-key matching with an escaped identifier containing `(` and no interior + space (`\rst(a)`, IEEE 1800-2017 §5.6.1 — an escaped identifier ends at + whitespace): built a real module with this port name, instantiated it in + three files, and drove the actual engine (not a hand-built title) through + `offered`/`code_actions`/`resolve`. The offer's menu matched the eager + menu, the title genuinely carried the literal `` `\rst(a)` `` including the + paren, and `key()` still isolated the trailing count phrase correctly — the + dev's reasoning in the comment on `key` holds under an adversarial name. + (One test-authoring pitfall found and fixed on my own scratch test, not a + product bug: `ports.rs`'s pre-existing `qa_escaped_module_name_ + instantiation_parity_with_whole_workspace` also builds a `Tree::new( + "qa_escaped")`, and reusing that same name in my own scratch test raced the + two tests over the same temp directory under parallel `cargo test` + execution, producing spurious failures in both. Renamed my scratch tree and + the collision was gone on repeated runs. `Tree::new` keys its temp directory + on the string name alone with no per-test-function salt, which is a latent + hazard for the *next* test added under the same name — not something this + feature's diff introduced or should fix, flagging it here rather than in + the diff.) +- Capability gate over the wire (scratch test in `tests/e2e.rs`, two shapes in + one loop): `resolveSupport` present but its `properties` list `["documentation"]` + (no `"edit"`), and `capabilities: {}` with no `codeAction` key at all. Both + got the eager shape — `data` null, `edit` inline with the real + `WorkspaceEdit` — over an actual `initialize` → `didOpen` → + `textDocument/codeAction` session, not just the unit test of + `code_action_resolve_support` in isolation. +- Large-file mode: confirmed by reading `server/large_file.rs`'s + `document_uri` (`params.get("textDocument")?...`) — a `codeAction/resolve` + request's params are a bare `CodeAction`, which has no `textDocument` key, + so `large_file_answer` returns `None` unconditionally for this method and + the request falls through to `dispatch.rs`'s normal arm, where `ports:: + resolve`'s own `.filter(|doc| !doc.large)` refuses it. Re-ran the dev's + `a_resolve_against_a_buffer_on_the_large_file_fast_path_is_refused` — passes, + no panic. +- Cost/timing, re-derived independently over the wire against the real + opentitan checkout (confirmed still 128 files instantiate `prim_flop_2sync` + today via `grep`), read-only throughout: + - Built `lucisv-server` v0.40.0 in a scratch worktree + (`git worktree add /private/tmp/.../scratchpad/base v0.40.0`, `cargo build + --release -p lucisv_server`, then `git worktree remove` — the one git + command used outside status/diff), and wrote a small throwaway Node driver + (`scratchpad/time_code_action.js`, modeled on `editors/vscode/smoke.js`'s + framing) to time a real `textDocument/codeAction` at the + `prim_flop_2sync` instantiation in `hw/ip/aon_timer/rtl/aon_timer.sv`, + workspace-scoped via `initializationOptions.lucisv.index.scope`. + - v0.40.0 server, eager (no `resolveSupport`): 76.4 / 76.4 / 77.8 ms repeats. + - This branch's server, eager (no `resolveSupport`): 77.3 / 76.2 / 77.7 ms + repeats — statistically identical to v0.40.0, confirming no regression for + a client that cannot resolve. + - This branch's server, **offer** (`resolveSupport: ["edit"]`): 4.76 / 4.38 + / 4.25 ms repeats — about **16× faster**, both with 0 actions returned + (the same "worst case: full cost, nothing offered" shape §6a complained + about). + - Also re-ran the dev's own ignored perf probe + (`ports::tests::the_offer_is_flat_where_the_eager_answer_grows`) directly: + eager 656 µs–15.6 ms across 3/40/128 fan-out, offer 55–78 µs flat — closely + matches the table in this README (§37.1 "Measured"). + - **Note, not a finding against this feature:** my repeat numbers (~76 ms + eager) are well under `performance_take2.md` §6a's originally recorded + 184.9–186.2 ms for this exact shape. Both old and new servers agree with + each other on *this* machine, so it reads as a machine/measurement-harness + difference from whatever produced §6a's numbers, not a regression — the + relative number this feature is judged on (offer vs. eager, same server, + same request) is the clean ~16× and it holds. +- `offer_sources`'s read set: re-ran the dev's `the_offer_reads_the_buffer_ + and_at_most_the_declaring_file` — one file at a port declaration, the buffer + plus the declaring file (never the instantiating tops or noise files) at an + instantiation. + +**§37.2 — the `inlayHint` zero at the default scope.** + +- Verified the finding independently against the **real** opentitan checkout, + read-only: `find . -iname pins_if.sv` → exactly one hit, + `hw/dv/sv/common_ifs/pins_if.sv`, confirmed outside `hw/ip/aes` entirely (a + sibling library folder the default scope's raise-to-`hw/ip/aes` widen does + not reach). +- Wrote a scratch, `#[ignore]`d test in `inlay.rs` (guarded, read-only) that + opens the real `hw/ip/aes/dv/tb/tb.sv` at the shipped default scope and + asserts: the widen reached files under `hw/ip/aes` but none under + `common_ifs`; `nav::definition`, `hover::hover` and `inlay_hints` all answer + nothing about the `pins_if` instantiation. All three held. Agree with the + dev's finding: this is a scope-reach question, not an inlay-hint bug, and + every neighbour using the same `module_definition` lookup is equally blind + to it at this scope. +- `git -C ~/repo/opentitan status --porcelain` unchanged after every read + (the same three pre-existing modifications). + +**§37.3 — `locate::definition_location` index-only path.** + +- Re-ran every pin in `locate.rs` and `nav.rs`; all pass. +- Extra encoding attacks beyond the dev's own (BOM, CRLF, multi-byte, astral): + a **tab-indented** declaration, and a declaration **after a lone `\r`** + (old-Mac line ending, not `\n`) — both agree between the index-only and + file-read paths exactly. (First attempt at the lone-`\r` case put it inside + a line comment and found zero declarations at all: `lexer.rs`'s line-comment + scanner runs to the next `\n` only, so a bare `\r` inside a comment does not + end it and the intended module got swallowed into the comment text — a + pre-existing, unrelated lexer property, not a locate.rs bug. Moved the `\r` + outside the comment and the equality attack ran as intended.) +- An open buffer with an edit above the definition still answers from the + buffer's own current text, confirmed via the dev's `an_open_buffer_still_ + answers_from_the_buffer` (re-run) plus reasoning: `ws.document_for_path` + gates the index-only branch off whenever a buffer is open, whatever the + index recorded. +- `held_views()` is `#[cfg(test)]` — grep and the diff both confirm no + production caller; it cannot be reached outside a test build. +- Timing re-derived independently, read-only, over the real opentitan + checkout (3 976 indexed files, 200 targets): **index-only 390 ns/definition, + file-read 27.9 µs/definition** — matches the README's 0.40 µs / 27.7 µs + claim within run-to-run noise, same ~69–71× ratio. + `git -C ~/repo/opentitan status --porcelain` unchanged. + +**Gates, re-run myself, guarded:** + +- `cargo clippy --all-targets` — clean, no warnings (checked both with and + without my scratch tests present). +- `tools/guard.sh -- cargo test --workspace` — **3 734 passed, 0 failed, 44 + ignored**, matching the dev's own gate exactly. No guard kill. +- `tools/guard.sh -- tools/corpus_check.sh` — **814/820 (99.3%)**, the same + six failures, `verification-error: none`, `crash: none`. +- `tools/guard.sh -- node editors/vscode/smoke.js target/release/lucisv-server` + — OK, 20 messages. +- `git -C ~/repo/opentitan status --porcelain` after every opentitan read, + throughout the session: unchanged, the same three pre-existing + modifications every time. +- Scratch worktree at `/private/tmp/.../scratchpad/base` (v0.40.0) removed + with `git worktree remove` after use; `git worktree list` shows only the + main tree. + +**Findings.** None at HIGH or MEDIUM severity. Two LOW, informational, neither +in this feature's own diff: +- LOW — `ports.rs`'s test-scratch `Tree::new` keys its temp directory on the + caller-supplied string alone, with no per-test salt; two tests choosing the + same name race under parallel execution (reproduced against the pre-existing + `qa_escaped_module_name_instantiation_parity_with_whole_workspace`). Not + part of this diff and not blocking; worth a name-collision guard (e.g. + salt with the test's `#[test]` function name) if it bites again. +- LOW — the offer/eager repeat-timing numbers measured this session (~76 ms + eager, ~4.5 ms offer, both machines) are well under `performance_take2.md` + §6a's recorded 184.9–186.2 ms for the identical 128-file-fan-out shape; + old and new servers agree with each other on this machine, so it reads as + environment drift from whatever produced §6a's numbers rather than a + regression this feature introduced. Recorded for whoever next revisits + §6a's absolute numbers. + +**Verdict: PASS.** + +## Review + +**2026-09-04 — lead.** Accepted; ships in 0.41.0. 37.1 is the shape §10 +asked for and the numbers say why: the offer is flat (53–68 µs from a +3-file to a 128-file fan-out, on both cursor shapes) where the eager path +is linear, and over the wire on opentitan's worst case QA measured the +offer at ~4.5 ms against ~77 ms eager — the cursor-move request is off the +fan-out. The dev's five deviations are all right: matching on the title's +key rather than the exact title is forced by the plan's own unsaved-buffer +requirement, and the escaped-identifier attack (`\rst(a)`) shows the key +holds; refusing a resolve on a large buffer closes a gate the fast path's +URI check cannot see; keeping the eager unsaved-buffer pin beside its +lazy sibling is correct because the eager path is still live for clients +that cannot resolve. 37.2 is ruled as the dev framed it: the zero is +correct — `pins_if` is declared outside what the default scope reaches +from `tb.sv`, definition and hover answer nothing there either, and QA +confirmed it on the real tree — so this is a *scope* question, not an +inlay defect, and the §10 line is closed as investigated. 37.3 is a pure +fast path (index-only Location equal to the file-read one over every +encoding shape QA and the dev tried, 69× cheaper, no view created), with +the honest exclusion of open buffers whose indexed spans may be stale. +QA's two LOWs are noted, not actioned: `Tree::new` takes a per-test name +and the existing names are distinct, and §6a's absolute numbers were +measured on a different day's machine state — both servers agree with +each other here, which is what the comparison needed. diff --git a/docs/features/server-lint/README.md b/docs/features/server-lint/README.md index 58f03c5..04cba9e 100644 --- a/docs/features/server-lint/README.md +++ b/docs/features/server-lint/README.md @@ -188,7 +188,13 @@ code_action_provider: Some(CodeActionProviderCapability::Options(CodeActionOptio `Options` rather than `Simple(true)` on purpose: a client that filters by kind (which is how fix-on-save is configured) has to be told which kinds exist. -`resolve_provider` is `None` because every action is returned complete. +`resolve_provider` was `None` because every action was returned complete; +since TODO §37.1 it is `Some(true)` and a third kind +(`refactor.rewrite.lucisv.ports`) is listed. The quick fixes above are +unaffected — the actions that are now offered without their edits are the port +refactorings, and only to a client that declared +`textDocument.codeAction.resolveSupport.properties: ["edit"]`. See +`docs/features/lazy-code-action/README.md`. **Still deliberately not advertised**, unchanged by this round and absent from the initialize result rather than present-and-false: `rangeFormatting` (waits on @@ -227,8 +233,15 @@ TODO §2 `--lines`), `completion`, `rename`, `signatureHelp`, and cross-file - [x] ~~**Not done:** fence-aware fixes (Handshake 3) — a quick fix can edit inside a `// verilog_format: off` region, where `lucisv check --fix` would not.~~ Delivered by **shared-fence-filter** (round 14). -- [ ] **Not done:** `codeAction/resolve`. Every action is cheap to build in - full; lazy resolution is a payload optimization for actions that are not. +- [x] ~~**Not done:** `codeAction/resolve`. Every action is cheap to build in + full; lazy resolution is a payload optimization for actions that are + not.~~ Delivered by **lazy-code-action** (TODO §37.1), and the note was + right about *these* actions: the quick fixes and `source.fixAll.lucisv` + are still returned complete. What is now lazy is the **port + refactorings**, whose offer used to compute the whole cross-file edit — + 185–201 ms at a 128-file fan-out, on every cursor move. `resolve` hands + an action that already carries its edit straight back, so a client that + resolves everything it was offered still gets these unchanged. - [x] ~~**Not done:** sharing one parse with the linter (Handshake 1).~~ Delivered by **one-parse** (round 19).