LSP §9c: workspace file operations — renames rewrite includes
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:
1 parent
bf17ddd1e5
commit
45db6cd14f
9 files changed
+2524
-27
No files matched your search
File diff suppressed because it is too large.
Load diff
@@ -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 {
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
Reference in new issue
Block a user