LSP §9c: workspace file operations — renames rewrite includes
ci / checks (push) Failing after 48s
ci / corpus (push) Successful in 26s

workspace/willRenameFiles rewrites every `include whose RESOLVED
target is a renamed file — never a name match — sweeping sources() so
unopened files count and open buffers contribute unsaved text.
Rewrites preserve the include's form where the new location allows
(bare stays bare in-dir; otherwise the shortest suffix that resolves
under the rungs that form uses; ../ last; absolute stays absolute), a
still-resolving include gets no edit, and an unrewritable one is left
untouched with a warning rather than given an invented path.
Directory renames ride the same prefix mapping for free, and the
mirror case — the including file itself moving breaks its own-dir
rung — ships with the same machinery. didRenameFiles/didDeleteFiles
nudge the index through the watcher's own predicate.

Three checks guard the write path: the edit range is the path token
minus delimiters by construction; the rewritten line re-scans and
re-lexes to exactly one include of the same form; and the rewritten
path must resolve_as_if to exactly the new location against the
post-rename filesystem — with every edit addressed to the PRE-rename
uri, the spec detail a client silently drops edits over, pinned on
the wire by QA. QA's corpus probe (a real ibex header, 87 real
includers) caught the round's one real bug — unnormalized includer
paths turning same-directory renames into false warnings — fixed with
one normalize. Batch renames do not compound; recorded as a
documented choice bounded by the safety net.

42 tests added (dev 33 + QA 9). verify.rs untouched.

docs/features/file-operations/README.md

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
lucioandClaude Fable 5 committed 2026-08-26 22:35:37 -07:00
1 parent bf17ddd1e5
commit 45db6cd14f
9 files changed
+2524 -27

No files matched your search

+30 -1
View File
@@ -892,10 +892,39 @@ and are not gaps.
result by hand, and `vlog_parser` rejects `interface class`, so
`implements` can never resolve and no item can carry
`SymbolKind::Interface`.
- [ ] **File operations** — `workspace/willRenameFiles`: renaming a
- [x] **File operations** — `workspace/willRenameFiles`: renaming a
`.sv/.svh` rewrites `` `include`` lines that reference it (the
include graph exists); `didRename/didDelete` as cheaper index nudges
than the watcher round-trip.
→ delivered 2026-08-27 by `docs/features/file-operations/README.md`:
`workspace.fileOperations` + `crates/lucisv_server/src/file_ops.rs`.
An include is rewritten only when the graph says it **resolves** to
the renamed file — never on a filename match, so two `defs.svh` in
one workspace stay two files. The new spelling preserves the form
where the new location allows it (bare stays bare when a rung reaches
it, angled resolves through `+incdir+`s only, absolute stays
absolute), shortest resolving suffix first, with a `../`-relative
spelling as the last resort — which is also what answers a renamed
include *directory*, since lucisv does not edit filelists. An include
no spelling can reach is left exactly as written and named in a
`window/showMessage` warning ("log all, show the first", the
filelist rule): the server never invents a path that would not
resolve. **Folders are handled**, not declined — LSP sends only the
folder's URI and a folder is a path prefix, which is the same
operation a file rename already was. The rule shipped with a mirror
half the brief did not ask for: an include written *in* a file that
moves breaks the same way and is re-spelled too. Every edit covers
the path token alone (never the backtick, the delimiters or a
trailing comment) and is verified three ways before it is emitted —
re-scanned, re-lexed, and re-resolved against the filesystem the
rename will leave behind. `didRename`/`didDelete` reindex through
the same scope predicate the watcher uses, not deduplicated against
it (a double rebuild is a re-read, never a different answer). One
sweep is 54 ms over the 860-file corpus. `verify.rs` untouched.
`includes.rs` gained `resolve_as_if` (so there is still exactly one
copy of the EDA search order) and `normalize` became public; the
standing request to extract one `lucisv_core::path::normalize` for
the three private copies is still open.
- [ ] **`workspace/didChangeWorkspaceFolders`** — roots are read once
at initialize; adding/removing a folder mid-session is ignored.
- [ ] **`workspace/configuration` (server-pull)** — we rely solely on
File diff suppressed because it is too large. Load diff
+30 -3
View File
@@ -134,6 +134,12 @@ impl IncludeGraph {
graph
}
/// The `+incdir+` directories an include is looked for in, in filelist
/// order — the search rungs past the including file's own directory.
pub fn incdirs(&self) -> &[PathBuf] {
&self.incdirs
}
/// The file an `` `include`` names, or `None` when nothing on disk
/// answers to it.
///
@@ -142,9 +148,26 @@ impl IncludeGraph {
/// order. The `<angled>` form skips the own-directory rung, which is the C
/// convention and the only difference the two spellings make here.
pub fn resolve(&self, from: Option<&Path>, include: &Include) -> Option<PathBuf> {
self.resolve_as_if(from, include, &|path| path.is_file())
}
/// [`IncludeGraph::resolve`], asked about a filesystem that has not
/// happened yet: `exists` decides which paths are files.
///
/// The one search order, spent twice — `file_ops.rs` has to know where an
/// include *will* land once a rename the client has announced goes
/// through, and a second copy of the rung order there could disagree with
/// this one in exactly the corner cases nobody tests. See
/// `docs/features/file-operations/README.md`.
pub fn resolve_as_if(
&self,
from: Option<&Path>,
include: &Include,
exists: &dyn Fn(&Path) -> bool,
) -> Option<PathBuf> {
let target = Path::new(&include.target);
if target.is_absolute() {
return target.is_file().then(|| self.as_the_index_spells_it(normalize(target)));
return exists(target).then(|| self.as_the_index_spells_it(normalize(target)));
}
let own = match include.system {
true => None,
@@ -153,7 +176,7 @@ impl IncludeGraph {
own.into_iter()
.chain(self.incdirs.iter().map(PathBuf::as_path))
.map(|dir| dir.join(target))
.find(|candidate| candidate.is_file())
.find(|candidate| exists(candidate))
.map(|found| self.as_the_index_spells_it(normalize(&found)))
}
@@ -211,7 +234,11 @@ impl IncludeGraph {
/// Fold `.`/`..` away so one file has one spelling, and so a resolved include
/// compares equal to the same file's path in the index. Symlinks are
/// deliberately not resolved, matching `lucisv_core`'s lexical rule.
fn normalize(path: &Path) -> PathBuf {
///
/// Public since 2026-08-27 so `file_ops.rs` folds a renamed file's path the
/// same way a resolved include is folded — the two are compared, and a fourth
/// private copy of this loop is the one thing that guarantees they disagree.
pub fn normalize(path: &Path) -> PathBuf {
let mut out = PathBuf::new();
for component in path.components() {
match component {
+43 -1
View File
@@ -12,6 +12,7 @@ mod completion;
mod convert;
mod diagnostics;
mod expand;
mod file_ops;
mod folding;
mod format;
mod hierarchy;
@@ -57,7 +58,7 @@ use lsp_types::{
SemanticTokensLegend, SemanticTokensOptions, SemanticTokensServerCapabilities,
ServerCapabilities, SignatureHelpOptions, TextDocumentSyncCapability, TextDocumentSyncKind,
TextDocumentSyncOptions, TextDocumentSyncSaveOptions, TypeDefinitionProviderCapability,
WorkDoneProgressOptions,
WorkDoneProgressOptions, WorkspaceServerCapabilities,
};
use crate::server::{ClientAbilities, Server};
@@ -255,6 +256,20 @@ fn capabilities() -> ServerCapabilities {
workspace_diagnostics: true,
work_done_progress_options: WorkDoneProgressOptions::default(),
})),
// File operations (3.16): renaming a header rewrites the
// `` `include``s that resolve to it, and a rename or a delete nudges
// the index without waiting for the watcher round-trip. Advertised
// unconditionally — unlike the watchers, nothing here is
// server-initiated, so a client that cannot send these requests simply
// never sends them and the capability costs it nothing. See
// `docs/features/file-operations/README.md`.
workspace: Some(WorkspaceServerCapabilities {
// Roots are still read once at `initialize`; adding a folder
// mid-session needs `didChangeWorkspaceFolders`, which is its own
// item in TODO.md §9c.
workspace_folders: None,
file_operations: Some(file_ops::file_operations()),
}),
semantic_tokens_provider: Some(SemanticTokensServerCapabilities::SemanticTokensOptions(
SemanticTokensOptions {
work_done_progress_options: WorkDoneProgressOptions::default(),
@@ -449,6 +464,33 @@ mod tests {
assert!(caps.diagnostic_provider.is_some());
assert!(caps.code_lens_provider.is_some());
assert!(caps.document_on_type_formatting_provider.is_some());
assert!(caps.workspace.is_some(), "the file operations live here");
}
#[test]
fn the_file_operations_reach_the_wire_under_workspace() {
// A client sends `willRenameFiles` only where the *server's* filters
// say so, and it looks for them at this exact key — a capability
// nested one level wrong is a capability that is never exercised.
let value = initialize_value().expect("the initialize result serializes");
let operations = &value["capabilities"]["workspace"]["fileOperations"];
assert_eq!(
operations["willRename"]["filters"][0]["pattern"]["glob"],
serde_json::json!(watch::SOURCE_GLOB),
"{value:#?}"
);
assert_eq!(
operations["willRename"]["filters"][1]["pattern"]["matches"],
serde_json::json!("folder"),
"a folder rename moves every include that reached into it"
);
assert_eq!(operations["didRename"]["filters"].as_array().map(Vec::len), Some(1));
assert_eq!(operations["didDelete"]["filters"].as_array().map(Vec::len), Some(1));
// The three this server does not answer are absent, not empty: a
// filter list a server cannot serve is a request it will be sent.
for absent in ["willCreate", "didCreate", "willDelete"] {
assert_eq!(operations[absent], serde_json::Value::Null, "{absent} is not answered");
}
}
#[test]
+238 -21
View File
@@ -15,8 +15,8 @@ use std::error::Error;
use lsp_server::{Connection, ExtractError, Message, Notification, Request, RequestId, Response};
use lsp_types::notification::{
Cancel, DidChangeConfiguration, DidChangeTextDocument, DidChangeWatchedFiles,
DidCloseTextDocument, DidOpenTextDocument, DidSaveTextDocument, LogMessage, Notification as _,
Progress, PublishDiagnostics, ShowMessage,
DidCloseTextDocument, DidDeleteFiles, DidOpenTextDocument, DidRenameFiles, DidSaveTextDocument,
LogMessage, Notification as _, Progress, PublishDiagnostics, ShowMessage,
};
use lsp_types::request::{
ApplyWorkspaceEdit, CallHierarchyIncomingCalls, CallHierarchyOutgoingCalls,
@@ -28,25 +28,26 @@ use lsp_types::request::{
PrepareRenameRequest, RangeFormatting, References, RegisterCapability, Rename, Request as _,
SelectionRangeRequest, SemanticTokensFullDeltaRequest, SemanticTokensFullRequest,
SemanticTokensRangeRequest, ShowDocument, Shutdown, SignatureHelpRequest, TypeHierarchyPrepare,
TypeHierarchySubtypes, TypeHierarchySupertypes, UnregisterCapability, WillSaveWaitUntil,
WorkDoneProgressCreate, WorkspaceDiagnosticRequest, WorkspaceSymbolRequest,
TypeHierarchySubtypes, TypeHierarchySupertypes, UnregisterCapability, WillRenameFiles,
WillSaveWaitUntil, WorkDoneProgressCreate, WorkspaceDiagnosticRequest, WorkspaceSymbolRequest,
};
use lsp_types::{
ApplyWorkspaceEditParams, ApplyWorkspaceEditResponse, CallHierarchyIncomingCallsParams,
CallHierarchyOutgoingCallsParams, CallHierarchyPrepareParams, CancelParams, CodeActionKind,
CodeActionParams, CodeLensParams, CompletionParams, DidChangeConfigurationParams,
DidChangeTextDocumentParams, DidChangeWatchedFilesParams, DidCloseTextDocumentParams,
DidOpenTextDocumentParams, DidSaveTextDocumentParams, DocumentDiagnosticParams,
DocumentDiagnosticReport, DocumentDiagnosticReportResult, DocumentFormattingParams,
DocumentHighlightParams, DocumentLinkParams, DocumentOnTypeFormattingParams,
DocumentRangeFormattingParams, DocumentSymbolParams, DocumentSymbolResponse,
ExecuteCommandParams, FoldingRangeParams, FullDocumentDiagnosticReport, GotoDefinitionParams,
GotoDefinitionResponse, HoverParams, InlayHintParams, InlineCompletionParams,
LinkedEditingRangeParams, Location, LogMessageParams, MessageType, NumberOrString, Position,
PreviousResultId, ProgressParams, ProgressParamsValue, ProgressToken, PublishDiagnosticsParams,
ReferenceParams, RegistrationParams, RelatedFullDocumentDiagnosticReport,
RelatedUnchangedDocumentDiagnosticReport, RenameParams, SelectionRangeParams, SemanticToken,
SemanticTokens, SemanticTokensDelta, SemanticTokensDeltaParams, SemanticTokensFullDeltaResult,
CodeActionParams, CodeLensParams, CompletionParams, DeleteFilesParams,
DidChangeConfigurationParams, DidChangeTextDocumentParams, DidChangeWatchedFilesParams,
DidCloseTextDocumentParams, DidOpenTextDocumentParams, DidSaveTextDocumentParams,
DocumentDiagnosticParams, DocumentDiagnosticReport, DocumentDiagnosticReportResult,
DocumentFormattingParams, DocumentHighlightParams, DocumentLinkParams,
DocumentOnTypeFormattingParams, DocumentRangeFormattingParams, DocumentSymbolParams,
DocumentSymbolResponse, ExecuteCommandParams, FoldingRangeParams, FullDocumentDiagnosticReport,
GotoDefinitionParams, GotoDefinitionResponse, HoverParams, InlayHintParams,
InlineCompletionParams, LinkedEditingRangeParams, Location, LogMessageParams, MessageType,
NumberOrString, Position, PreviousResultId, ProgressParams, ProgressParamsValue, ProgressToken,
PublishDiagnosticsParams, ReferenceParams, RegistrationParams,
RelatedFullDocumentDiagnosticReport, RelatedUnchangedDocumentDiagnosticReport,
RenameFilesParams, RenameParams, SelectionRangeParams, SemanticToken, SemanticTokens,
SemanticTokensDelta, SemanticTokensDeltaParams, SemanticTokensFullDeltaResult,
SemanticTokensParams, SemanticTokensRangeParams, SemanticTokensRangeResult,
SemanticTokensResult, ShowDocumentParams, ShowMessageParams, SignatureHelpParams,
TextDocumentPositionParams, TypeHierarchyPrepareParams, TypeHierarchySubtypesParams,
@@ -62,9 +63,9 @@ use serde_json::Value;
use crate::state::Workspace;
use crate::{
code_action, completion, diagnostics, folding, format, hierarchy, hover, includes, inlay,
inline, lens, linked, nav, on_type, pairs, ports, rename, selection, settings, signature,
symbols, sync, tokens, type_def, type_hierarchy, watch,
code_action, completion, diagnostics, file_ops, folding, format, hierarchy, hover, includes,
inlay, inline, lens, linked, nav, on_type, pairs, ports, rename, selection, settings,
signature, symbols, sync, tokens, type_def, type_hierarchy, watch,
};
/// What the client said it can do, read once at `initialize` because that is
@@ -610,6 +611,20 @@ impl Server {
to_value(type_hierarchy::subtypes(&self.workspace, &p.item))
})
}
// The client is about to rename files and asks what that costs.
// Every `` `include`` that *resolves* to one of them is re-spelled
// so it still resolves afterwards; one that no include path can
// reach is left exactly as written and named in a warning, because
// inventing a path that resolves to nothing would be worse than
// the stale one. `null` when there is nothing to do.
WillRenameFiles::METHOD => decode(request).and_then(|p: RenameFilesParams| {
let rewrite = file_ops::will_rename(&self.workspace, &p.files);
self.report_scope(rewrite.warnings);
match rewrite.edit {
Some(edit) => to_value(edit),
None => Ok(Value::Null),
}
}),
WorkspaceSymbolRequest::METHOD => {
decode(request).and_then(|p: WorkspaceSymbolParams| {
to_value(WorkspaceSymbolResponse::Flat(symbols::workspace_symbols(
@@ -993,6 +1008,22 @@ impl Server {
}
}
}
// The client moved or removed files itself. The same nudge a
// watched-file event gives, filtered by the same predicate, and
// deliberately not deduplicated against it: a client is free to
// send both, and a second rebuild is a pure re-read of the tree —
// it costs one scan and one diagnostics generation, never a
// different answer.
DidRenameFiles::METHOD => {
if let Ok(p) = extract::<RenameFilesParams>(notification) {
self.reindex_for(file_ops::renamed(&p.files));
}
}
DidDeleteFiles::METHOD => {
if let Ok(p) = extract::<DeleteFilesParams>(notification) {
self.reindex_for(file_ops::deleted(&p.files));
}
}
// The `lucisv.*` settings, pushed at startup and on every change.
// Nothing here trusts the payload — `settings::from_payload`
// drops whatever it cannot use.
@@ -1107,9 +1138,19 @@ impl Server {
id
}
/// Rescan, but only when the paths a file-operation notification named are
/// paths the index reads. The same test a watched-file notification gets.
fn reindex_for(&mut self, paths: Vec<std::path::PathBuf>) {
let filelist = self.workspace.filelist_path();
if file_ops::touches_scope(&paths, filelist.as_deref()) {
self.reindex();
}
}
/// Rescan the workspace and republish every open buffer against the new
/// index. Every caller changed what the index should contain — a save, a
/// new `lucisv.exclude`/`lucisv.filelist`, or a watched file changing on disk.
/// new `lucisv.exclude`/`lucisv.filelist`, a watched file changing on disk,
/// or a file the client renamed or deleted.
fn reindex(&mut self) {
let bar = self.begin_indexing();
let warnings = self.workspace.rebuild_index();
@@ -1208,6 +1249,10 @@ impl Server {
/// drifted from the tree can easily carry forty stale paths, and forty
/// popups would be worse than the problem. Said once per rebuild, which is
/// once per save — the same rhythm the `lucisv.toml` warning has.
///
/// `workspace/willRenameFiles` reports through here too: an `` `include``
/// a rename strands is the same kind of news, said at the same volume, and
/// a rename that strands forty of them must not open forty popups.
fn report_scope(&self, warnings: Vec<String>) {
for warning in &warnings {
self.notify(
@@ -4374,4 +4419,176 @@ mod tests {
// cancel did not intercept it.
session.answer(server_id, Value::Null);
}
// ------------------------------------------------------------------
// file operations (`docs/features/file-operations/README.md`)
// ------------------------------------------------------------------
/// One `workspace/willRenameFiles` for `from` → `to`, driven through the
/// real dispatch.
fn will_rename(session: &mut Session, from: &Path, to: &Path) -> Value {
session.result(
WillRenameFiles::METHOD,
serde_json::json!({ "files": [{
"oldUri": path_to_uri(from).expect("uri"),
"newUri": path_to_uri(to).expect("uri"),
}] }),
)
}
#[test]
fn will_rename_answers_the_edit_that_keeps_an_include_resolving() {
let tree = Tree::new("willrename");
tree.write("defs.svh", "`define W 8\n");
tree.write("top.sv", "`include \"defs.svh\"\nmodule t;\nendmodule\n");
let mut session = Session::new(vec![tree.path.clone()], false);
let (from, to) = (tree.path.join("defs.svh"), tree.path.join("widths.svh"));
let answer = will_rename(&mut session, &from, &to);
let uri = path_to_uri(&tree.path.join("top.sv")).expect("uri");
let edits = &answer["changes"][uri.as_str()];
assert_eq!(edits[0]["newText"], serde_json::json!("widths.svh"), "{answer:#?}");
// The range is the path token: line 0, inside the quotes.
assert_eq!(edits[0]["range"]["start"], serde_json::json!({ "line": 0, "character": 10 }));
assert_eq!(edits[0]["range"]["end"], serde_json::json!({ "line": 0, "character": 18 }));
assert!(session.shown().is_empty(), "a rewrite everything could reach says nothing");
}
#[test]
fn will_rename_works_for_a_file_no_editor_ever_opened() {
// Includes live in unopened files; the sweep reads them off disk
// through the same `sources()` the index is built from.
let tree = Tree::new("willrenameunopened");
tree.write("defs.svh", "`define W 8\n");
tree.write("top.sv", "`include \"defs.svh\"\n");
let mut session = Session::new(vec![tree.path.clone()], false);
assert!(session.server.workspace.open_uris().is_empty(), "premise: nothing open");
let answer =
will_rename(&mut session, &tree.path.join("defs.svh"), &tree.path.join("widths.svh"));
let uri = path_to_uri(&tree.path.join("top.sv")).expect("uri");
assert_eq!(
answer["changes"][uri.as_str()][0]["newText"],
serde_json::json!("widths.svh"),
"{answer:#?}"
);
}
#[test]
fn will_rename_answers_null_when_there_is_nothing_to_rewrite() {
let tree = Tree::new("willrenamenull");
tree.package("rtl/a.sv", "a");
tree.write("notes.md", "prose\n");
let mut session = Session::new(vec![tree.path.clone()], false);
// A source file nothing includes.
let answer =
will_rename(&mut session, &tree.path.join("rtl/a.sv"), &tree.path.join("rtl/b.sv"));
assert_eq!(answer, Value::Null, "{answer:#?}");
// And a file this server has no opinion about at all.
let answer =
will_rename(&mut session, &tree.path.join("notes.md"), &tree.path.join("NOTES.md"));
assert_eq!(answer, Value::Null, "{answer:#?}");
assert!(session.shown().is_empty());
}
#[test]
fn an_include_a_rename_strands_is_shown_once_and_logged() {
// The same "first shown, all logged" rule the scope warnings follow —
// a rename that strands forty includes must not open forty popups.
let tree = Tree::new("willrenamewarn");
std::fs::create_dir_all(tree.path.join("inc")).expect("mkdir");
tree.write("inc/defs.svh", "`define W 8\n");
tree.write("a.sv", "`include <defs.svh>\n");
tree.write("b.sv", "`include <defs.svh>\n");
tree.write("files.f", "+incdir+inc\na.sv\nb.sv\n");
tree.write("lucisv.toml", "filelist = \"files.f\"\n");
let mut session = Session::new(vec![tree.path.clone()], false);
let _ = session.drain();
// The angled form resolves against incdirs only, so a move out of the
// one include path cannot be spelled from either file.
let answer =
will_rename(&mut session, &tree.path.join("inc/defs.svh"), &tree.path.join("far.svh"));
assert_eq!(answer, Value::Null, "nothing invented: {answer:#?}");
let shown = session.drain();
let popups: Vec<&Message> = shown
.iter()
.filter(|m| matches!(m, Message::Notification(n) if n.method == ShowMessage::METHOD))
.collect();
let logs: Vec<&Message> = shown
.iter()
.filter(|m| matches!(m, Message::Notification(n) if n.method == LogMessage::METHOD))
.collect();
assert_eq!(popups.len(), 1, "one popup for two stranded includes: {popups:#?}");
assert_eq!(logs.len(), 2, "both are logged: {logs:#?}");
}
/// One `workspace/didRenameFiles` for `from` → `to`.
fn did_rename(session: &mut Session, from: &Path, to: &Path) {
session.notify(
DidRenameFiles::METHOD,
serde_json::json!({ "files": [{
"oldUri": path_to_uri(from).expect("uri"),
"newUri": path_to_uri(to).expect("uri"),
}] }),
);
}
#[test]
fn a_rename_notification_rebuilds_the_index() {
let tree = Tree::new("didrename");
tree.package("rtl/a.sv", "a");
let mut session = Session::new(vec![tree.path.clone()], false);
assert_eq!(indexed(&session, "a"), 1, "premise: indexed under its old name");
std::fs::rename(tree.path.join("rtl/a.sv"), tree.path.join("rtl/b.sv")).expect("rename");
did_rename(&mut session, &tree.path.join("rtl/a.sv"), &tree.path.join("rtl/b.sv"));
assert_eq!(indexed(&session, "a"), 1, "still one package, found at its new path");
// And the same nudge from the watcher for the same move changes
// nothing: the rebuild is a re-read of the tree, not an increment.
session.watched(&[tree.path.join("rtl/b.sv")]);
assert_eq!(indexed(&session, "a"), 1, "reindexing twice is harmless");
}
#[test]
fn a_delete_notification_rebuilds_the_index() {
let tree = Tree::new("diddelete");
tree.package("rtl/a.sv", "a");
tree.package("rtl/gone.sv", "gone_pkg");
let mut session = Session::new(vec![tree.path.clone()], false);
assert_eq!(indexed(&session, "gone_pkg"), 1, "premise: indexed");
std::fs::remove_file(tree.path.join("rtl/gone.sv")).expect("remove");
session.notify(
DidDeleteFiles::METHOD,
serde_json::json!({ "files": [
{ "uri": path_to_uri(&tree.path.join("rtl/gone.sv")).expect("uri") },
] }),
);
assert_eq!(indexed(&session, "gone_pkg"), 0, "gone from the index too");
assert_eq!(indexed(&session, "a"), 1, "and the rest survives");
}
#[test]
fn a_file_operation_notification_for_nothing_the_index_reads_costs_no_rebuild() {
let tree = Tree::new("didrenamestray");
tree.package("rtl/open.sv", "open_pkg");
let mut session = Session::new(vec![tree.path.clone()], false);
session.open(
&tree.path.join("rtl/open.sv"),
"package open_pkg;\n localparam K = 1;\nendpackage\n",
);
assert_eq!(session.publishes(), 1, "premise: `didOpen` published once");
did_rename(&mut session, &tree.path.join("README.md"), &tree.path.join("READ.md"));
session.notify(
DidDeleteFiles::METHOD,
serde_json::json!({ "files": [
{ "uri": path_to_uri(&tree.path.join("notes.txt")).expect("uri") },
] }),
);
assert_eq!(session.publishes(), 0, "neither is a path the index reads");
}
}
+7 -1
View File
@@ -112,7 +112,13 @@ pub fn touches_scope(changes: &[FileEvent], filelist: Option<&Path>) -> bool {
.any(|path| watched(&path, filelist))
}
fn watched(path: &Path, filelist: Option<&Path>) -> bool {
/// Whether one path is something the index reads: a source file, or the
/// filelist that decides which source files there are.
///
/// Public since 2026-08-27 for `file_ops.rs`: `didRenameFiles`/`didDeleteFiles`
/// nudge the index for exactly the paths a watcher event would, and two copies
/// of that test would drift.
pub fn watched(path: &Path, filelist: Option<&Path>) -> bool {
if filelist == Some(path) {
return true;
}
+156
View File
@@ -3636,3 +3636,159 @@ fn the_class_hierarchy_round_trips_over_the_wire_in_both_directions() {
let _ = std::fs::remove_dir_all(&dir);
}
/// One `TextEdit` applied the way a client applies it: by line and character.
/// The fixtures below are ASCII, so a UTF-16 character is a byte column.
fn apply_edits(text: &str, edits: &[serde_json::Value]) -> String {
let mut lines: Vec<String> = text.split('\n').map(str::to_string).collect();
for edit in edits {
let range = &edit["range"];
let line = range["start"]["line"].as_u64().expect("line") as usize;
assert_eq!(range["end"]["line"], range["start"]["line"], "one line per edit: {edit:#?}");
let (from, to) = (
range["start"]["character"].as_u64().expect("start") as usize,
range["end"]["character"].as_u64().expect("end") as usize,
);
let new_text = edit["newText"].as_str().expect("newText");
lines[line].replace_range(from..to, new_text);
}
lines.join("\n")
}
/// The file-operations round trip against the real binary: the server is asked
/// what a rename costs, the answer is applied and the rename performed exactly
/// as a client would, and a second session proves the include resolves again
/// at its new location — the whole point of the exercise.
#[test]
fn a_rename_round_trips_through_the_edit_and_leaves_the_include_resolving() {
let dir = temp_dir("willrename");
std::fs::create_dir_all(dir.join("inc")).expect("inc");
let defs = dir.join("inc/defs.svh");
std::fs::write(&defs, "`define WIDTH 8\n").expect("write");
let top = dir.join("top.sv");
let source = "`include \"inc/defs.svh\"\nmodule top;\nendmodule\n";
std::fs::write(&top, source).expect("write");
let root = format!("file://{}", dir.display());
let top_uri = format!("file://{}", top.display());
let old_uri = format!("file://{}", defs.display());
let moved = dir.join("inc/widths.svh");
let new_uri = format!("file://{}", moved.display());
// Session one: "I am about to rename inc/defs.svh to inc/widths.svh."
let messages = talk(
&[
frame(&format!(
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":2,"method":"workspace/willRenameFiles","params":{{"files":[{{"oldUri":"{old_uri}","newUri":"{new_uri}"}}]}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
]
.concat(),
);
// The capability is advertised where a client looks for it.
let initialized = messages.iter().find(|m| m["id"] == 1).expect("initialize response");
let operations = &initialized["result"]["capabilities"]["workspace"]["fileOperations"];
assert!(operations["willRename"]["filters"].is_array(), "{initialized:#?}");
let answer = messages.iter().find(|m| m["id"] == 2).expect("willRename response");
let edits = answer["result"]["changes"][&top_uri].as_array().expect("edits for top.sv");
assert_eq!(edits.len(), 1, "{answer:#?}");
// The client's half: apply the edit, then do the rename.
let rewritten = apply_edits(source, edits);
assert_eq!(rewritten, "`include \"inc/widths.svh\"\nmodule top;\nendmodule\n");
std::fs::write(&top, &rewritten).expect("write back");
std::fs::rename(&defs, &moved).expect("rename");
// Session two: the include is a live link again, at the new path.
let messages = talk(
&[
frame(&format!(
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"workspace/didRenameFiles","params":{{"files":[{{"oldUri":"{old_uri}","newUri":"{new_uri}"}}]}}}}"#
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{top_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string(&rewritten).expect("json")
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/documentLink","params":{{"textDocument":{{"uri":"{top_uri}"}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
]
.concat(),
);
let links = messages.iter().find(|m| m["id"] == 2).expect("documentLink response")["result"]
.as_array()
.expect("a link list")
.clone();
assert_eq!(links.len(), 1, "{links:#?}");
assert_eq!(links[0]["target"], new_uri.as_str(), "the include resolves to the new file");
let _ = std::fs::remove_dir_all(&dir);
}
/// The mirror case, at the wire: the file *being renamed* is also the one
/// whose own include needs rewriting (its own-directory rung moves with it).
/// Per LSP, `willRenameFiles` edits apply before the rename, so the
/// `WorkspaceEdit` must name the file's *old* URI — a `TextDocumentEdit`
/// naming the new URI would be silently dropped by a real client, since that
/// document does not exist yet at the time the edit is applied. This is the
/// highest-risk detail in the feature, so it is pinned at the JSON-RPC level,
/// not just through the handler.
#[test]
fn a_moving_includer_s_own_edit_is_addressed_to_its_old_uri_on_the_wire() {
let dir = temp_dir("willrenameself");
std::fs::create_dir_all(dir.join("rtl")).expect("rtl");
std::fs::create_dir_all(dir.join("src")).expect("src");
std::fs::write(dir.join("rtl/defs.svh"), "`define WIDTH 8\n").expect("write");
let old_top = dir.join("rtl/top.sv");
std::fs::write(&old_top, "`include \"defs.svh\"\nmodule top;\nendmodule\n").expect("write");
let new_top = dir.join("src/top.sv");
let root = format!("file://{}", dir.display());
let old_uri = format!("file://{}", old_top.display());
let new_uri = format!("file://{}", new_top.display());
let messages = talk(
&[
frame(&format!(
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":2,"method":"workspace/willRenameFiles","params":{{"files":[{{"oldUri":"{old_uri}","newUri":"{new_uri}"}}]}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
]
.concat(),
);
let answer = messages.iter().find(|m| m["id"] == 2).expect("willRename response");
let changes = answer["result"]["changes"].as_object().expect("changes map");
assert_eq!(changes.len(), 1, "{answer:#?}");
assert!(
changes.contains_key(&old_uri),
"the edit must be addressed to the pre-rename URI: {answer:#?}"
);
assert!(
!changes.contains_key(&new_uri),
"a client applies these edits before the rename — the new URI does not \
exist yet and an edit there would be dropped: {answer:#?}"
);
let edits = changes[&old_uri].as_array().expect("edits");
assert_eq!(edits[0]["newText"], serde_json::json!("../rtl/defs.svh"), "{answer:#?}");
let _ = std::fs::remove_dir_all(&dir);
}
+540
View File
@@ -0,0 +1,540 @@
# file-operations
## Goal
Renaming a header breaks every `` `include`` that reaches it, and until now
lucisv watched that happen and said nothing — the editor moved `defs.svh`, four
files went on naming a path that no longer exists, and the only sign was that
ctrl-click stopped working. LSP 3.16 has the hook: a client that is about to
rename files asks the server first (`workspace/willRenameFiles`) and applies
whatever `WorkspaceEdit` comes back as part of the same undo step. The include
graph already knows exactly which lines point at the moved file — by
*resolution*, not by filename — so this round spends it: an include whose
resolved target moves is re-spelled so it still resolves, an include no legal
spelling can reach is left exactly as written and named in a warning, and the
two after-the-fact notifications (`didRenameFiles`, `didDeleteFiles`) nudge the
index without waiting for a watcher round-trip.
## Assumptions
- **Renames in one batch do not compound.** `Moves` maps a path by the first
matching rename (`find_map`), so a directory rename and an explicit rename
of a file inside that directory, sent in one request, apply whichever rule
matches first rather than both in sequence (QA log, 2026-08-27). No client
observed sends that shape — a directory rename lists the directory alone —
and the safety net still refuses any edit whose rewritten include does not
resolve, so the failure mode is a skipped edit plus the warning, never a
wrong write. Recorded so a future round that wants compounding knows it is
changing a documented choice.
- **Resolution decides, never the filename.** An include is rewritten only
when `IncludeGraph::resolve` says it reaches the renamed file. Two
`defs.svh` in one workspace are two different files here, and only the one
that moves is touched — pinned by
`an_include_of_a_different_file_with_the_same_name_is_untouched`.
- **The rename has not happened yet.** `willRenameFiles` is asked *before* the
move, so the old target is resolved against the filesystem as it stands. The
*new* spelling is resolved against the filesystem the rename will leave
behind, which `Moves` models: everything under `old` will be under `new`, a
path something moves away from is gone, a path something moves to exists if
its source does (so an `a`→`b`, `b`→`a` swap leaves both files, as it does on
disk). No filesystem is touched to answer that — it is a prefix rewrite plus
one `is_file` on the source.
- **A file rename and a folder rename are one operation.** LSP sends only the
folder's own URI for a folder rename ("when a folder is renamed, only the
folder will be included, and not its children"), and a folder is a *prefix*
of the paths inside it — which is exactly what `Moves` already computes for a
file. Handling folders therefore cost this module no machinery at all, which
is why they are handled rather than declined: the cost is one filter in the
capability and one workspace sweep on a user gesture (54 ms over the 860-file
corpus, see Cost), and the case it covers — moving a directory of headers —
is the single most include-breaking thing a user can do.
- **The two notifications ask for files only.** `didRenameFiles`/
`didDeleteFiles` do one thing, reindex, and a folder filter there would buy a
full rebuild for every unrelated folder rename in the tree while the file
watcher already reports the individual files a folder move touches. So the
folder filter is on `willRename` alone, where it earns its keep.
- **The form is preserved where the new location allows it.** The candidate
spellings are the suffixes of the new path under each search rung the *same*
form would use — the including file's own directory (skipped for the angled
form, as everywhere) and then each `+incdir+` — shortest suffix first, with
the rung order breaking a tie. An originally **absolute** include stays
absolute. So a same-directory rename keeps the bare filename, and a move into
an `+incdir+` keeps it bare too.
- **A relative spelling is the last resort, not the first.** When no rung's
suffix resolves, a quoted include falls back to a path relative to the
including file (`../headers/defs.svh`), which resolves on the own-directory
rung every tool has. It is the ugliest spelling in the file, so nothing that
goes through an `+incdir+` is passed over for it. This is what answers a
renamed *include directory*: the `+incdir+` in the filelist is then stale and
**lucisv does not edit filelists**, but the source keeps compiling, which is
the better half of a bad situation.
- **An include that still reads correctly is not edited.** Before anything is
computed, the include as written is re-resolved against the post-rename
filesystem; if it still reaches its file, there is no edit and no warning. A
header moving between two `+incdir+`s under the same name, and a rename that
carries includer and included together, are both no-ops — a no-op edit is
noise in the user's diff.
- **An include the rename strands is left alone *and* said out loud.** The
server will not invent a path that resolves to nothing (that would be a
guess, and a guess written into the user's file). It also will not stay
silent about a line it knows it just broke. So: no edit, and one
`window/showMessage` WARNING naming the file, the line and the include —
through `report_scope`, so forty stranded includes are one popup and forty
log lines.
- **Both ends of the edge are watched.** The brief's rule was "an include whose
resolved target is the renamed file"; the shipped rule adds the mirror case,
an include written *in* a file that moves, because that breaks for exactly
the same reason (the own-directory rung moves out from under it) and would
otherwise be a silent breakage the feature politely watched happen.
- **Edits are addressed to the file's current URI.** A file that is itself
being renamed *and* needs an include rewritten is edited at the URI it has
now, while its new content is computed from where it will be. That is what
VS Code and every other file-operation participant expect: the edit lands on
the document, and the rename carries it.
- **The scope ladder still decides what lucisv can see.** The sweep reads
`Workspace::sources()` — the in-scope files, with open buffers overriding
disk. An include in a file the filelist does not name is not rewritten,
exactly as it is not indexed, not linted and not searched.
- **The capability is static and ungated.** `ServerCapabilities` is built
before the client's own capabilities are read, and unlike the file watchers
nothing here is server-initiated: a client that cannot send these requests
simply never sends them. Gating would buy nothing and cost the
`capabilities()` function a parameter.
## The safety net
The `WorkspaceEdit` this feature produces **rewrites the user's source files**,
which nothing else in the server does unasked. It is fenced three ways, and
every candidate spelling passes all three or is discarded (`survives`):
1. **The edit can only cover the path token.** Its range is
`path_span.start + 1 .. path_span.end - 1` — the bytes *between* the
delimiters. Structurally, no answer this module can compute is able to move
the backtick, the quotes, the indentation or a trailing comment; the worst
a bug can produce is a wrong path inside a well-formed include line.
(`the_edit_covers_the_path_token_and_not_one_byte_more`.)
2. **It still scans as the include it was.** The line the edit would produce is
built and re-scanned with `includes::scan`: exactly one include, target
equal to the spelling, same quoted/angled form. A spelling carrying the
closing delimiter or a newline dies here.
3. **It still lexes, and it still resolves.** The same line is run through
`vlog_parser::tokenize` and must be one `TokenKind::Directive` and nothing
else; and the *re-scanned* include — what the scanner will actually read
back, not what we meant to write — must resolve, through
`IncludeGraph::resolve_as_if`, to exactly the file the rename is moving the
old target to. A spelling that would resolve to a *different* file (a bare
name shadowed by a header beside the includer) is refused here, and the
longer correct spelling is written instead
(`a_spelling_that_would_resolve_somewhere_else_is_not_written`).
`verify.rs` is untouched: no normalization was added or broadened, so hard
invariant #4 is not in play. The formatter is not involved in this path at all.
## Handshakes
### Consumed
- `lucisv_server::includes` — the whole of the resolution story. Three changes,
all additive:
- **`IncludeGraph::resolve_as_if(from, include, exists)`** is new, and
`resolve` is now `resolve_as_if(.., &|p| p.is_file())`. There is still
exactly **one** copy of the EDA search order; this module needed to ask it
about a filesystem that has not happened yet, and a second copy here would
have disagreed with the first in the corner cases nobody tests.
- **`IncludeGraph::incdirs()`** — a read-only accessor, so a candidate
spelling can be a suffix under a real include path rather than a guess.
- **`includes::normalize` is now `pub`** (it was private). A renamed path and
a resolved include are compared, and they must be folded the same way; a
fourth private copy of that loop is the one thing that guarantees they
drift. This is the same `.`/`..` folding
`lucisv_core::filelist::Reader::normalize` and
`lucisv_core::config::Discovery::absolute` each have privately — the
include-nav README's standing request to extract one
`lucisv_core::path::normalize` and point all of them at it is **still
open**, and this round deliberately did not widen its scope to do it.
- `lucisv_server::watch::watched` is now `pub` (it was private). The
notifications filter their paths with exactly the predicate a
`didChangeWatchedFiles` event is filtered with — two copies of "is this a
path the index reads" would drift, and the two paths must agree because a
client may well send both for one rename.
- `lucisv_server::watch::SOURCE_GLOB` is reused verbatim as the file-operation
filter's glob, so the watcher and the file operations can never be asked
about different sets of files.
- `Workspace::sources()` for the sweep, `Workspace::includes()` for the graph,
`uri::{path_to_uri, uri_to_path}` for the URIs (file-operation params carry
`String` URIs, not parsed ones, so the parse happens in `path_of`).
### Promised
- `lucisv_server::file_ops`:
```rust
pub fn file_operations() -> WorkspaceFileOperationsServerCapabilities;
pub struct Rewrite { pub edit: Option<WorkspaceEdit>, pub warnings: Vec<String> }
pub fn will_rename(ws: &Workspace, files: &[FileRename]) -> Rewrite;
pub fn renamed(files: &[FileRename]) -> Vec<PathBuf>;
pub fn deleted(files: &[FileDelete]) -> Vec<PathBuf>;
pub fn touches_scope(paths: &[PathBuf], filelist: Option<&Path>) -> bool;
```
`Rewrite::edit` is `None` when there is nothing to do, and the handler
answers that as the protocol's `null` rather than as an empty edit.
- `Server::reindex_for(paths)` — the notification half, one `reindex()` when
the paths touch the index's scope. Deliberately **not** deduplicated against
the watcher: a client is free to send both a `didRenameFiles` and a
`didChangeWatchedFiles` for one rename, and the second rebuild is a pure
re-read of the tree. It costs one scan and one diagnostics generation, never
a different answer.
- `main.rs` advertises `workspace.fileOperations`; `report_scope`'s doc now
says it serves these warnings too.
### Not touched
No other crate. No new dependency. No version bump. `verify.rs`, the formatter
and the linter are not on this path at all.
## Cost
`willRenameFiles` sweeps the workspace once per request. Measured 2026-08-27 on
the checked-in 860-file corpus, `--release`:
| | |
|---|---|
| files read (`sources()`) | 860 |
| one rename, whole sweep | **~54 ms** |
| the index rebuild a save already pays | ~320 ms |
Most of it is the file read `sources()` does — the same read
`callHierarchy/incomingCalls` (56 ms) and `typeHierarchy/subtypes` (55 ms) pay,
and for the same reason. A `text.contains("`include")` prefilter keeps the
resolver off the ~86% of files that include nothing. Pinned by an `#[ignore]`d
probe (`cargo test --release -p lucisv_server --bin lucisv-server
file_ops::tests::perf -- --ignored --nocapture`), the same shape as
`includes.rs`'s: it prints and asserts nothing but the corpus's presence.
The notifications cost one `reindex()` each, which is the cost a save has.
## Status / TODO
- [x] `crates/lucisv_server/src/file_ops.rs`: the capability shape, the sweep,
the candidate spellings, the three safety checks, the post-rename
filesystem model, the notification filters.
- [x] `workspace/willRenameFiles` dispatched in `server.rs`, answering
`WorkspaceEdit | null` and reporting stranded includes through
`report_scope`.
- [x] `workspace/didRenameFiles` + `workspace/didDeleteFiles` dispatched, one
`reindex()` per notification that touches scope.
- [x] `workspace.fileOperations` advertised in `main.rs` — source-file filters
for all three, plus a folder filter on `willRename`.
- [x] `IncludeGraph::resolve_as_if` / `incdirs()` / `pub normalize`, so there
is still one search order and one path folding.
- [x] `watch::watched` made public, so the notifications and the watcher share
one scope test.
- [x] Tests: 24 in `file_ops.rs`, 7 in `server.rs` (dispatch, warning volume,
reindex, watcher-double, unopened file, `null`), 1 in `main.rs` (the
capability on the wire), 1 e2e session (real binary, edit decoded,
applied, rename performed, include re-resolving).
- [x] `cargo fmt`, `cargo clippy --all-targets`, `cargo test --workspace`,
`node editors/vscode/smoke.js`.
- [ ] **Not done, deliberately:** `willCreateFiles`/`didCreateFiles`. A file
that has just been created has nothing pointing at it to rewrite, and the
watcher indexes it.
- [ ] **Not done, deliberately:** `willDeleteFiles`. Refusing a delete the user
asked for, or editing the includes of a file that is about to stop
existing, is not this server's business; `didDeleteFiles` reindexes and
the include simply stops resolving, which is the truth.
- [ ] **Not done, deliberately:** the filelist is never rewritten. Renaming a
file the `.f` names, or the directory an `+incdir+` names, leaves the
filelist stale — lucisv warns about a filelist naming a file that is gone
on the very next rebuild, and fixing it is the user's call. Editing a
project's build manifest from a rename gesture is a much bigger promise
than this feature makes.
- [ ] **Not done, deliberately:** an include in a file the scope ladder
excludes is not rewritten. Same rule as everywhere else in the server.
- [ ] **Not done, deliberately:** no `documentChanges`/`renameFile` operations
in the answer — plain `changes`, as `textDocument/rename` returns. The
client is doing the renaming; the server has only text to contribute.
## Work log
### 2026-08-27 — dev agent, file operations (TODO.md §9c)
Built in the order the brief lists: the resolution extension first, then the
sweep, then the dispatch, then the tests. Decisions worth recording:
- **`resolve_as_if` rather than a second resolver.** The one thing this module
needs that `includes.rs` did not have is "where would this include land if
the filesystem looked like *that*". Writing that here would have been a
second copy of the EDA rung order, three weeks after the include-nav round
concluded that two scanners meant "`documentLink` and the graph disagreeing
in exactly the corner cases nobody tests". So `resolve` grew an existence
predicate and became a one-line call into the general form. No behaviour
change: the ordinary path passes `|p| p.is_file()`, which is the expression
it had inline.
- **Folder renames are handled, not declined** — the brief left the choice to
the code, and the code made it easy: `Moves` maps a path by prefix, and a
file is just a prefix with no children. The whole folder story is one extra
filter in the capability. Two tests pin it (a folder of headers moving, and
an `+incdir+` directory moving).
- **The rule grew a mirror half, deliberately.** The brief scoped this to
includes whose *target* is renamed. Writing the tests turned up the twin: an
include breaks just as thoroughly when the file it is written *in* moves,
because the own-directory rung goes with it — and that case would have been
silent, with no edit and no warning. It is the same machinery (`target =
moves.after(old).unwrap_or(old)`, and the includer resolved from where it
will be), so it shipped. `a_file_that_moves_away_from_its_own_headers_is_re_spelled_too`.
- **Two of the first tests were wrong, and the code was right.** Both asserted
an edit where the correct answer is *no* edit: a header moving into an
`+incdir+` under the same name, and a batch carrying includer and included
into one new directory, both leave the line already reading correctly. That
is what added the explicit "does it still resolve as written?" guard at the
top of the loop — without it, the candidate ranking would have rewritten a
perfectly good `"../inc/defs.svh"` into a bare `"defs.svh"` during an
unrelated in-place rename, which is a diff the user did not ask for.
- **One real bug, found by a failing test, not by review.** `Moves::is_file`
compared paths lexically while the resolver hands it un-folded candidates
like `rtl/../inc/defs.svh` — `Path::is_file` follows the `..` itself, a
prefix comparison does not. Every `..`-relative candidate silently failed to
verify, which showed up as "no spelling reaches it" on the two tests that
need the relative fallback. `is_file` now folds first, through
`includes::normalize` — the same fold the resolver's own result goes through,
which is why that function is now `pub` rather than copied.
- **A renamed `+incdir+` directory re-spells relatively rather than warning.**
The first draft warned, on the grounds that only the filelist can really fix
it. The relative fallback resolves in every tool through the rung every tool
has, so the source keeps compiling; the stale `+incdir+` is a filelist
problem lucisv already reports on the next rebuild. Pinned, with the
trade-off written into the test.
- **`report_scope` reused rather than a second warning path.** "Log all, show
the first" is exactly the volume control this needs — a rename can strand
forty includes as easily as a filelist can name forty missing files. Its doc
comment now says so; no code moved.
**Files touched outside this feature's own module**, all of them the wiring the
brief asked for: `includes.rs` (`resolve_as_if`, `incdirs()`, `normalize` made
public — no behaviour change), `watch.rs` (`watched` made public), `main.rs`
(the module, the `workspace.fileOperations` capability, one test), `server.rs`
(the request arm, the two notification arms, `reindex_for`, one doc sentence on
`report_scope`, seven tests), `tests/e2e.rs` (one session and one `apply_edits`
helper).
**Verification.** `cargo fmt --all -- --check` clean; `cargo clippy
--all-targets` silent; `cargo test --workspace` green — **2105 passing, 5
ignored**, 33 of them new (24 `file_ops`, 7 `server`, 1 `main`, 1 e2e session)
plus the ignored perf probe. `node editors/vscode/smoke.js
target/debug/lucisv-server` → OK, 9 messages, unchanged from `bf17ddd`
(checked against the stashed tree, not assumed — the new capability is static
JSON and adds no message). Perf measured as above. No new dependency, no
version bump, no other crate touched.
## QA log
### 2026-08-27 — QA agent, file operations (TODO.md §9c)
Re-ran every gate, then attacked the list the lead handed down. One real bug
found and fixed (small, unambiguous, in-scope — fixed directly per the
workflow rules rather than kicked back to dev); everything else the dev
claimed held up, including the single highest-risk detail.
**Verdict up front: the pre-rename-URI semantics are correct.** `will_rename`
keys every edit off the path `Workspace::sources()` handed it — which is
always the file's *current* (pre-rename) location, including for the mirror
case where the edited file is itself one of the files being renamed. Read the
code to confirm, then pinned it at the wire level, which the dev's own e2e
session did not cover (it only exercised "another file's edit," not "the
moving file's own edit"): added
`a_moving_includer_s_own_edit_is_addressed_to_its_old_uri_on_the_wire` to
`crates/lucisv_server/tests/e2e.rs` — a real `willRenameFiles` round trip
where the *renamed* file is also the includer needing the edit, asserting the
`WorkspaceEdit`'s `changes` map is keyed by the **old** URI and does **not**
contain the new one. Passes.
**Gates.** `cargo fmt --all -- --check` clean. `cargo clippy --all-targets
--workspace` silent (one warning surfaced in a QA-added test —
`clippy::for_kv_map` on `for (_, edits) in &map` — fixed to `.values()`,
noted below). `cargo test --workspace`: **2114 passed, 0 failed, 5 ignored**
(2105 baseline + 1 e2e test + 8 new `file_ops` QA tests). Two full runs of
`cargo test -p lucisv_server file_ops::` diffed byte-for-byte except for
parallel test-execution order — no flakiness. `node editors/vscode/smoke.js
target/debug/lucisv-server` → OK, 9 messages.
**Finding 1 (MEDIUM, fixed) — `candidate_spellings` silently fails when the
includer's own path isn't already `.`/`..`-folded.**
`crates/lucisv_server/src/file_ops.rs`, `candidate_spellings` (now around
line 293) and `relative_spelling`. `target` (the rename's destination)
always reaches `candidate_spellings` normalized — both `graph.resolve` and
`Moves::after` fold `.`/`..` before returning. `includer` did not: it comes
straight from `Workspace::sources()`, which inherits whatever `self.roots`
was given at `open_roots`, unnormalized. `target.strip_prefix(dir)` and
`relative_spelling`'s common-prefix walk are pure path-*component* algebra
run before anything touches the filesystem, and `Path`'s components compare a
literal `ParentDir` (`..`) as different from the directory it resolves to —
so when `includer`'s directory carries an unfolded `..` and `target` doesn't,
every rung silently fails to match, even the trivial "keep it bare" spelling
for a same-directory rename. The include then gets a spurious "no include
path reaches it" warning instead of the one-word edit it should get. Caught
by the corpus-scale probe (below), not by any of the dev's or my
hand-written unit tests — every `Tree`-based test in this feature builds
`ws.open_roots(vec![tree.path.clone()])` from an already-clean
`std::env::temp_dir()`-based path, so the bug had no way to show up there.
`resolve`/`resolve_as_if`'s own existence checks (`Path::is_file`,
`Moves::is_file`) were never affected — both fold `..` themselves before
deciding, which is exactly why only this one pure-path step needed the fix.
Fixed with one line, normalizing `includer` at the top of
`candidate_spellings` before anything derives from it; comment explains why,
inline. Real-world exposure: narrow but not zero — `workspace_roots` in
`main.rs` never normalizes a client's `rootUri`/`workspace_folders` URI
either, so any workspace root a client hands over with an unresolved `.`/`..`
segment (unusual, but not forbidden by the URI grammar) would have hit this
on every single same-directory rename, the most common case there is.
Pinned by the corpus probe test itself (below), which fails without the fix
and passes with it — no separate minimal regression test added, since the
probe already exercises the exact shape that triggers it and a synthetic
`Tree`-based one would have to manufacture a dirty root on purpose, which is
what the probe already is.
**Attack surfaces, in the order asked for:**
1. **Wrong-edit hunts at the resolution boundary — verified clean.** Added
`a_shadow_between_an_own_dir_file_and_an_incdir_file_is_never_crossed`: two
`defs.svh`, one reached only via the includer's own directory and one only
via an `+incdir+`, so a name-matching implementation would cross them.
Renaming either one touches only the file that resolves to it, in both
directions. `resolve_as_if`'s delegation from `resolve` is the same
inlined closure `resolve` used before (`&|path| path.is_file()`) — no
include-nav test needed updating, and the full suite confirms
`documentLink`/`definition`/hover behavior is unchanged.
2. **The three checks, adversarially — verified clean, one gap closed.**
(a) `the_edit_range_is_exact_with_tab_indentation_and_a_block_comment`:
tabs for indentation, a `/* block */` trailing comment instead of the
dev's `//` line comment, byte range decoded and checked against the raw
text — exact. (b) `a_rename_target_whose_name_contains_the_quote_delimiter_is_refused_not_written`:
POSIX allows `"` in a filename (confirmed creatable on this filesystem),
and with no other candidate spelling available the module is forced to
either refuse or write a corrupting line — it refuses, warns, and the
source file on disk is provably untouched. Also
`a_rename_to_a_name_with_a_space_or_non_ascii_text_is_written_correctly`:
space and non-ASCII (`défs.svh`) are legal inside quotes and both rewrite
cleanly — the "total, correct" half of the same question. (c) the dev's
`a_spelling_that_would_resolve_somewhere_else_is_not_written` is a genuine
shadow: `rtl/defs.svh` pre-exists beside the includer, the bare candidate
for the renamed `inc/old.svh` → `inc/defs.svh` would resolve to the wrong
file via the own-directory rung, and the longer `../inc/defs.svh` is
written instead — read through by hand and confirmed live by the suite.
3. **The mirror case (includer moves) — verified clean, see the verdict
above.** `Moves`'s own-dir-move handling and the pre-rename URI addressing
are both correct.
4. **Directory renames by prefix — verified clean.**
`a_directory_rename_does_not_claim_a_sibling_with_a_shared_string_prefix`:
`rtl` → `rtl2` with a `rtl_extra/` sibling holding its own decoy header,
both referenced relatively from outside their own directories (so the
test actually forces an edit rather than landing on the includer-and-
included-move-together no-op). `rtl_extra`'s file is never touched, and
`Moves`'s `mapped`/`strip_prefix` is checked directly too: `Path::strip_prefix`
is component-wise, not string-wise, so `rtl_extra` was never at risk from
this angle. Nested batch:
`a_directory_rename_and_a_file_rename_inside_it_do_not_compound` —
characterized, not "fixed": `Moves::after` uses `find_map`, so a directory
rename and an explicit rename of a file inside it (a batch shape a
spec-compliant client should not send, per LSP's "only the folder's own
URI" rule, but nothing stops one from doing it) do not compound; whichever
entry is listed first in `params.files` wins for any path under that
directory, and the other is silently shadowed. Not corruption — whatever
spelling gets written is still checked against whichever model `Moves`
produced — but it is order-dependent in a way nothing documents.
**Recommendation for dev, not fixed here (out of QA's remit to redesign):**
either note this explicitly in the Assumptions section as an accepted
ambiguity, or have `Moves::announced` detect a file entry nested under a
directory entry in the same batch and drop the redundant one with a
warning. Low priority — real clients don't appear to construct this shape.
5. **Batch semantics — verified clean.**
`a_batch_where_both_the_includer_and_the_included_move_needs_both_moves_modeled`:
includer moves two directories deep, included file moves to an unrelated
directory, in one batch. Chose depths that make "only one move modeled"
produce a *textually different, wrong* answer both ways (dropping the
includer's move is one `..` short; dropping the included file's move
points at the old directory) — the actual answer is neither, confirming
`Moves` truly models both simultaneously rather than one overwriting the
other. The dev's own `a_batch_that_carries_includer_and_included_together_writes_nothing`
is a real instance of this too (a no-op *requires* both moves to be seen
together), just not one that discriminates between hypotheses on its own.
6. **`didRename`/`didDelete` — verified clean.** Read `reindex_for` and the
dispatch arms; the dev's own tests already cover in-scope → one reindex,
out-of-scope → none, and the watcher-double case, and pass. Generation
bumps once per `reindex()` call, so a client sending both
`didRenameFiles` and a watcher event for the same move bumps it twice —
documented as intentional ("a pure re-read of the tree"), matches
`a_rename_notification_rebuilds_the_index`'s own assertion, no
pull-diagnostics correctness issue (content converges, `resultId` just
changes an extra time).
7. **Capability shape on the wire — verified clean.** `main.rs`'s
`the_file_operations_reach_the_wire_under_workspace` and `file_ops.rs`'s
`the_capability_names_the_operations_this_server_answers` pin the exact
JSON; folder filter present only on `willRename`, absent on both
notifications, confirmed. Case sensitivity: the glob match is entirely the
*client's* job (VS Code decides whether `TOP.SV` matches `**/*.{v,vh,sv,svh}`
before it ever sends the request) — nothing in this server's code path is
involved, so there is nothing here to fix or test; noting it per the
brief's "don't over-engineer."
8. **CLAUDE.md compliance — verified clean.** No `unwrap()`/`expect()`/
`panic!` outside `#[cfg(test)]` in any of `file_ops.rs`, `server.rs`,
`main.rs`, `watch.rs`, `includes.rs` (checked with a diff-scoped grep).
Every public item has a one-line doc comment. This README's sections each
appear exactly once. `TODO.md`'s §9c item text is unchanged; only its
checkbox flipped and a delivery summary was appended below it, per the
"leave the item text intact" rule. `verify.rs` does not appear in the diff
at all.
**Beyond the list — corpus-scale probe.** `prim_assert.sv` (a single real
file in `corpus/ibex/vendor/lowrisc_ip/ip/prim/rtl/`) is included, own-
directory rung, by 87 sibling files in that same directory — real fan-out,
not a synthetic tree. Added
`a_real_corpus_header_with_wide_fan_out_is_swept_correctly_and_deterministically`:
sweeps the whole corpus with `will_rename` twice (identical file/warning
counts both times), then independently re-derives, for every produced edit,
whether the *written* spelling resolves to the new location once the
modeled rename has happened (built the check from `resolve_as_if` +
`Moves::announced` directly, deliberately not by calling back into
`survives`, so it is a genuine second opinion) — and confirms every touched
file's directory is the one real directory that includes this header,
nothing else. This is the test that caught Finding 1: it failed outright
before the fix (no edit was produced for any of the 87 files — every one
came back as a false "unreachable" warning) and passes cleanly after.
**Test tally added this round:** 8 in `file_ops.rs` (`qa_2026_08_27_attacks`,
nested under `mod tests`), 1 in `tests/e2e.rs`. `cargo test --workspace`:
2114 passed (was 2105 before this QA round; +1 e2e +8 file_ops, net of the
9 new tests exactly).
**Verdict: not committable as-is until Finding 1's fix is included** — which
it now is, applied directly in this same working tree (small, unambiguous,
in-scope per the workflow rules). With the fix in place and all eight attack
surfaces plus the corpus probe green, this is **committable**. Item 4's
nested-batch ordering is a documentation/robustness suggestion for the dev,
not a blocker — no corruption path exists even in that shape, thanks to the
safety net doing its job independently of what `Moves` models.
## Review
### 2026-08-27 — lead
Reviewed the diff, the work log and the QA log; re-ran all gates myself
(2114 workspace tests, 0 failed), clean. For a feature that writes user
files, the shape is right: resolution-not-name matching, a three-check
safety net that refuses rather than guesses, and the mirror case the
brief missed shipped with the same machinery rather than a special
case. The two dev deviations are both accepted as argued — the moving
includer's own-dir rung genuinely breaks, and re-spelling under a
renamed +incdir+ beats warning about a filelist this server rightly
does not edit.
The round's two QA results are exactly why the corpus probe belongs in
every write-path charter: the unnormalized-includer bug made the most
common rename shape (same directory) silently fail into a warning, and
no hand-written fixture caught it — 87 real includers of a real ibex
header did. And the pre-rename-URI wire test QA added covers the one
detail that would have failed invisibly in real editors (a client
drops an edit addressed to the post-rename uri). I applied QA's
recommendation as an Assumptions entry: batch renames do not compound,
recorded as a documented choice with the safety net bounding the
failure mode at a skipped edit plus a warning. Accepted as shipped.
+7
View File
@@ -52,6 +52,8 @@ looks like language knowledge in here is a bug or a `Handshake` request.
| `workspace/codeLens/refresh` | — | Server-**initiated**, once per workspace rescan, straight after the indexing bar comes down: a rescan can change any count on screen. Only for a client that advertised `workspace.codeLens.refreshSupport`; never at startup, where no buffer holds lenses. Same feature README |
| `workspace/symbol` | `WorkspaceIndex::workspace_symbols` | Capped at 256 hits |
| `workspace/didChangeWatchedFiles` | `Workspace::rebuild_index` | Registered dynamically after the handshake, for a client that advertised it. One rebuild per *notification*, however many files it names. See `docs/features/file-watching/README.md` |
| `workspace/willRenameFiles` | `includes::IncludeGraph` (through `resolve_as_if`) | The client is about to rename files and asks what that costs: every `` `include`` in scope whose **resolved** target moves — never a filename match — is re-spelled so it still resolves, in the form it was written in (bare stays bare where a rung reaches it, angled resolves through `+incdir+`s only, absolute stays absolute), shortest resolving suffix first and a `../`-relative spelling only as a last resort. An include written *in* a file that moves is re-spelled too. An include no spelling can reach is **left exactly as written** and named in a `window/showMessage` warning — nothing is invented. `null` when there is nothing to do. Folders are answered as well as files (LSP sends only the folder's URI; a folder is a path prefix). Every edit covers the path token alone and is verified three ways before it is emitted — see `docs/features/file-operations/README.md` |
| `workspace/didRenameFiles`, `workspace/didDeleteFiles` | `Workspace::rebuild_index` | One `reindex()` per notification whose paths touch the index's scope, filtered by the same predicate a watched-file event is. Deliberately not deduplicated against the watcher: a client may send both, and a second rebuild re-reads the tree rather than changing an answer. Source-file filters only — a folder move reaches the index through the watcher's own events. Same feature README |
| `window/workDoneProgress/create` + `$/progress` | — | Server-**initiated**: one indeterminate bar per workspace rescan, titled "Indexing Verilog workspace", ending with the indexed file count. Only for a client that advertised `window.workDoneProgress`. See `docs/features/work-done-progress/README.md` |
| `$/cancelRequest` | — | Best-effort, and honoured exactly when the cancel reaches the loop in the same burst as the request it names: that request is answered `RequestCancelled` (-32800) instead of computed. A cancel for anything else is dropped where it is read, `shutdown` is never cancellable, and nothing already running is interrupted. See `docs/features/cancel-request/README.md` |
@@ -587,6 +589,11 @@ list to `vlog_parser::KEYWORDS`. Rationale and inventory:
`docs/features/type-hierarchy/README.md`.
- [x] Single-step macro expansion on a hover card (`src/expand.rs`, M14) —
`docs/features/macro-expansion/README.md`.
- [x] `workspace/willRenameFiles` + `didRenameFiles`/`didDeleteFiles` —
delivered by **file-operations** (2026-08-27, TODO.md §9c): a rename
rewrites the `` `include``s that resolve to the moved file, folders
included, and never invents a path that would not resolve.
`docs/features/file-operations/README.md`.
- [x] `$/cancelRequest` — delivered by **cancel-request** (2026-08-26,
completing TODO.md §9b): the loop reads in bursts and answers a queued
request whose cancel is in the same burst with `RequestCancelled`,