File watching M9: the index notices the world changing

workspace/didChangeWatchedFiles via dynamic registration (globs for the
four source extensions plus the configured filelist's own path), one
rebuild per notification with the same warning surfacing as save, and
re-registration when vfmt.filelist moves. Registration happens in
Server::new because lsp-server's initialize_finish consumes the
initialized notification - the protocol-suggested handler would be dead
code (verified against the vendored source). Open-buffer overlays
survive rebuilds; malformed and out-of-scope events rebuild nothing.
git pull, external editors and filelist edits now land without a save.

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
lucioandClaude Fable 5 committed 2026-08-24 23:51:39 -07:00
1 parent fa38fd9dec
commit ab7beb1e54
9 files changed
+1395 -57

No files matched your search

+1 -1
View File
@@ -601,7 +601,7 @@ section only tracks the milestones.
rainbow's pair data.
- [x] **M8 `inlay-hints`** — port-name hints on ordered connections and
parameter-name hints on ordered `#(...)` overrides, from the index.
- [ ] **M9 `file-watching`** — `workspace/didChangeWatchedFiles` for
- [x] **M9 `file-watching`** — `workspace/didChangeWatchedFiles` for
sources and the filelist; reindex on external changes (git pull,
filelist edits outside the editor).
- [ ] **M10 `include-nav`** — clickable `` `include`` lines resolved
+7 -3
View File
@@ -29,6 +29,7 @@ mod symbols;
mod templates;
mod tokens;
mod uri;
mod watch;
use std::error::Error;
use std::path::PathBuf;
@@ -43,7 +44,7 @@ use lsp_types::{
TextDocumentSyncCapability, TextDocumentSyncKind, WorkDoneProgressOptions,
};
use crate::server::Server;
use crate::server::{ClientAbilities, Server};
use crate::uri::uri_to_path;
fn main() -> Result<(), Box<dyn Error + Sync + Send>> {
@@ -54,10 +55,13 @@ fn main() -> Result<(), Box<dyn Error + Sync + Send>> {
// field we want is optional anyway.
let params: InitializeParams = serde_json::from_value(params).unwrap_or_default();
let roots = workspace_roots(&params);
let snippets = snippet_support(&params);
let abilities = ClientAbilities {
snippets: snippet_support(&params),
file_watching: watch::dynamic_registration(&params),
};
connection.initialize_finish(id, serde_json::to_value(initialize_result())?)?;
Server::new(connection, roots, snippets).run()?;
Server::new(connection, roots, abilities).run()?;
io_threads.join()?;
Ok(())
}
+518 -29
View File
@@ -10,25 +10,27 @@ use std::error::Error;
use lsp_server::{Connection, ExtractError, Message, Notification, Request, RequestId, Response};
use lsp_types::notification::{
DidChangeConfiguration, DidChangeTextDocument, DidCloseTextDocument, DidOpenTextDocument,
DidSaveTextDocument, LogMessage, Notification as _, PublishDiagnostics, ShowMessage,
DidChangeConfiguration, DidChangeTextDocument, DidChangeWatchedFiles, DidCloseTextDocument,
DidOpenTextDocument, DidSaveTextDocument, LogMessage, Notification as _, PublishDiagnostics,
ShowMessage,
};
use lsp_types::request::{
CodeActionRequest, Completion, DocumentHighlightRequest, DocumentSymbolRequest, ExecuteCommand,
FoldingRangeRequest, Formatting, GotoDefinition, HoverRequest, InlayHintRequest,
PrepareRenameRequest, RangeFormatting, References, Rename, Request as _,
SemanticTokensFullRequest, SignatureHelpRequest, WorkspaceSymbolRequest,
PrepareRenameRequest, RangeFormatting, References, RegisterCapability, Rename, Request as _,
SemanticTokensFullRequest, SignatureHelpRequest, UnregisterCapability, WorkspaceSymbolRequest,
};
use lsp_types::{
CodeActionKind, CodeActionParams, CompletionParams, DidChangeConfigurationParams,
DidChangeTextDocumentParams, DidCloseTextDocumentParams, DidOpenTextDocumentParams,
DidSaveTextDocumentParams, DocumentFormattingParams, DocumentHighlightParams,
DocumentRangeFormattingParams, DocumentSymbolParams, DocumentSymbolResponse,
ExecuteCommandParams, FoldingRangeParams, GotoDefinitionParams, GotoDefinitionResponse,
HoverParams, InlayHintParams, LogMessageParams, MessageType, Position,
PublishDiagnosticsParams, ReferenceParams, RenameParams, SemanticTokensParams,
SemanticTokensResult, ShowMessageParams, SignatureHelpParams, TextDocumentPositionParams, Uri,
WorkspaceSymbolParams, WorkspaceSymbolResponse,
DidChangeTextDocumentParams, DidChangeWatchedFilesParams, DidCloseTextDocumentParams,
DidOpenTextDocumentParams, DidSaveTextDocumentParams, DocumentFormattingParams,
DocumentHighlightParams, DocumentRangeFormattingParams, DocumentSymbolParams,
DocumentSymbolResponse, ExecuteCommandParams, FoldingRangeParams, GotoDefinitionParams,
GotoDefinitionResponse, HoverParams, InlayHintParams, LogMessageParams, MessageType, Position,
PublishDiagnosticsParams, ReferenceParams, RegistrationParams, RenameParams,
SemanticTokensParams, SemanticTokensResult, ShowMessageParams, SignatureHelpParams,
TextDocumentPositionParams, UnregistrationParams, Uri, WorkspaceSymbolParams,
WorkspaceSymbolResponse,
};
use serde::de::DeserializeOwned;
use serde_json::Value;
@@ -36,9 +38,20 @@ use serde_json::Value;
use crate::state::Workspace;
use crate::{
code_action, completion, diagnostics, folding, format, hover, inlay, nav, pairs, ports, rename,
settings, signature, symbols, tokens,
settings, signature, symbols, tokens, watch,
};
/// What the client said it can do, read once at `initialize` because that is
/// the only time those capabilities are sent.
pub struct ClientAbilities {
/// Whether the client can expand a completion item's tabstops.
pub snippets: bool,
/// Whether the client accepts a `workspace/didChangeWatchedFiles`
/// registration. There is no static form of that capability, so a client
/// that says nothing keeps the save-only staleness model.
pub file_watching: bool,
}
/// Everything the server owns.
pub struct Server {
connection: Connection,
@@ -47,17 +60,42 @@ pub struct Server {
/// for a document whenever its text changes, so the warning is said once
/// per file change rather than once per format-on-save.
config_warnings: HashSet<Uri>,
/// Whether the client said it can expand a completion item's tabstops.
/// Read once, at `initialize`, because that is the only time it is sent.
snippets: bool,
abilities: ClientAbilities,
/// The id of the file-watcher registration in force, if any. Kept so a
/// changed `vfmt.filelist` can replace it: the watched filelist path is
/// part of the registration, so a new path needs a new registration.
watchers: Option<String>,
/// Numbers the file-watcher registrations, so a replacement can name the
/// one it supersedes.
registrations: u32,
/// Numbers the requests made *of* the client. A repeated id is a protocol
/// error, so this only ever counts up.
request_ids: u32,
}
impl Server {
pub fn new(connection: Connection, roots: Vec<std::path::PathBuf>, snippets: bool) -> Server {
pub fn new(
connection: Connection,
roots: Vec<std::path::PathBuf>,
abilities: ClientAbilities,
) -> Server {
let mut workspace = Workspace::default();
let warnings = workspace.open_roots(roots);
let server = Server { connection, workspace, config_warnings: HashSet::new(), snippets };
let mut server = Server {
connection,
workspace,
config_warnings: HashSet::new(),
abilities,
watchers: None,
registrations: 0,
request_ids: 0,
};
server.report_scope(warnings);
// The earliest legal moment: `main` builds this only after
// `initialize_finish`, which returns once the client's `initialized`
// notification has arrived — and consumes it, so the loop below never
// sees one to hang the registration off instead.
server.register_watchers();
server
}
@@ -73,8 +111,10 @@ impl Server {
self.connection.sender.send(Message::Response(response))?;
}
Message::Notification(notification) => self.notification(notification),
// Nothing is requested *of* the client except the messages
// below, which want no answer.
// The only thing asked *of* the client is (un)registering the
// file watchers, and there is nothing to do with the answer:
// a client that refuses simply keeps the save-only model, and
// it says so on its own log, not ours.
Message::Response(_) => {}
}
}
@@ -243,7 +283,7 @@ impl Server {
Completion::METHOD => decode(request).and_then(|p: CompletionParams| {
let at = p.text_document_position;
let (uri, position) = (at.text_document.uri, at.position);
completion::completions(&self.workspace, &uri, position, self.snippets)
completion::completions(&self.workspace, &uri, position, self.abilities.snippets)
.map_or(Ok(Value::Null), to_value)
}),
SignatureHelpRequest::METHOD => decode(request).and_then(|p: SignatureHelpParams| {
@@ -366,24 +406,44 @@ impl Server {
if let Some(text) = p.text {
self.set_document(p.text_document.uri.clone(), text);
}
// A save is one of the two things that rebuild the index;
// the other is a change to `vfmt.exclude` below. The
// staleness window that opens is in the feature README.
// A save is one of the things that rebuild the index; the
// others are a change to `vfmt.exclude`/`vfmt.filelist`
// below, and a watched file changing on disk. The
// staleness window that is left is in the feature README.
self.reindex();
}
}
// Something changed on disk that no buffer told us about — a `git
// pull`, a checkout, a generated file, an externally edited
// filelist. One rebuild per *notification*, never one per file:
// the params carry a list, and a checkout fills it.
DidChangeWatchedFiles::METHOD => {
if let Ok(p) = extract::<DidChangeWatchedFilesParams>(notification) {
let filelist = self.workspace.filelist_path();
if watch::touches_scope(&p.changes, filelist.as_deref()) {
self.reindex();
}
}
}
// The `vfmt.*` settings, pushed at startup and on every change.
// Nothing here trusts the payload — `settings::from_payload`
// drops whatever it cannot use.
DidChangeConfiguration::METHOD => {
if let Ok(p) = extract::<DidChangeConfigurationParams>(notification) {
let pushed = settings::from_payload(&p.settings);
// Only `exclude` changes which files exist as far as this
// server is concerned; the other two are read afresh by
// the next formatting request and need no invalidation.
let watched = self.workspace.filelist_path();
// Only `exclude` and `filelist` change which files exist
// as far as this server is concerned; the other two are
// read afresh by the next formatting request and need no
// invalidation.
if self.workspace.set_client_settings(pushed) {
self.reindex();
}
// The watched filelist path is baked into the
// registration, so a new one needs a new registration.
if self.workspace.filelist_path() != watched {
self.register_watchers();
}
}
}
DidCloseTextDocument::METHOD => {
@@ -403,9 +463,43 @@ impl Server {
// outgoing
// ------------------------------------------------------------------
/// Ask the client to watch the source files and the filelist for us,
/// replacing any registration already in force.
///
/// Silent for a client that cannot be asked — that one keeps the save-only
/// staleness model, which is what it had before this feature existed.
fn register_watchers(&mut self) {
if !self.abilities.file_watching {
return;
}
// Unregister first, so a client that keys watchers by id is never
// holding two registrations that both fire for `**/*.sv`.
if let Some(id) = self.watchers.take() {
let params = UnregistrationParams { unregisterations: vec![watch::unregistration(id)] };
self.send_request(UnregisterCapability::METHOD, params);
}
let filelist = self.workspace.filelist_path();
let registration = watch::registration(self.registrations, filelist.as_deref());
self.registrations += 1;
self.watchers = Some(registration.id.clone());
let params = RegistrationParams { registrations: vec![registration] };
self.send_request(RegisterCapability::METHOD, params);
}
/// Ask the client something. The answer is ignored (see `run`), but the id
/// must still be unique — a repeated one is a protocol error.
fn send_request(&mut self, method: &str, params: impl serde::Serialize) {
let id = RequestId::from(format!("vfmt-{}", self.request_ids));
self.request_ids += 1;
let request = Request::new(id, method.to_string(), params);
// A closed channel means the client is gone; there is nobody left to
// report the failure to.
let _ = self.connection.sender.send(Message::Request(request));
}
/// Rescan the workspace and republish every open buffer against the new
/// index. Both callers changed what the index should contain — a save, or
/// a new `vfmt.exclude`.
/// index. Every caller changed what the index should contain — a save, a
/// new `vfmt.exclude`/`vfmt.filelist`, or a watched file changing on disk.
fn reindex(&mut self) {
let warnings = self.workspace.rebuild_index();
self.report_scope(warnings);
@@ -525,3 +619,398 @@ fn extract<P: DeserializeOwned>(
let method = notification.method.clone();
notification.extract(&method)
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use lsp_types::{FileChangeType, FileEvent};
use crate::uri::path_to_uri;
/// A scratch workspace root, removed on drop.
struct Tree {
path: PathBuf,
}
impl Tree {
fn new(name: &str) -> Tree {
let path = std::env::temp_dir()
.join(format!("vfmt_server_watch_{}_{name}", std::process::id()));
let _ = std::fs::remove_dir_all(&path);
std::fs::create_dir_all(&path).expect("temp dir");
Tree { path }
}
/// A package declaring one localparam, so the index can be asked
/// whether this file was scanned at all.
fn package(&self, rel: &str, name: &str) {
let path = self.path.join(rel);
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).expect("parent");
}
std::fs::write(&path, format!("package {name};\n localparam K = 1;\nendpackage\n"))
.expect("write");
}
fn write(&self, rel: &str, text: &str) {
std::fs::write(self.path.join(rel), text).expect("write");
}
}
impl Drop for Tree {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.path);
}
}
/// A real `Server` on an in-memory connection, plus the client end of it —
/// so a test can drive a notification and read every message it produced.
struct Session {
server: Server,
client: Connection,
}
impl Session {
fn new(roots: Vec<PathBuf>, file_watching: bool) -> Session {
let (server_end, client) = Connection::memory();
let abilities = ClientAbilities { snippets: false, file_watching };
let server = Server::new(server_end, roots, abilities);
Session { server, client }
}
fn notify(&mut self, method: &str, params: impl serde::Serialize) {
self.server.notification(Notification::new(method.to_string(), params));
}
/// Everything the server has said since the last drain.
fn drain(&self) -> Vec<Message> {
self.client.receiver.try_iter().collect()
}
/// The requests the server has made of the client, as (method, params).
fn requests(&self) -> Vec<(String, Value)> {
self.drain()
.into_iter()
.filter_map(|message| match message {
Message::Request(request) => Some((request.method, request.params)),
_ => None,
})
.collect()
}
/// How many diagnostics publishes the server pushed since the last
/// drain. With exactly one open buffer this counts index rebuilds:
/// `reindex` republishes every open document, once.
fn publishes(&self) -> usize {
self.drain()
.iter()
.filter(|message| match message {
Message::Notification(n) => n.method == PublishDiagnostics::METHOD,
_ => false,
})
.count()
}
fn open(&mut self, path: &Path, text: &str) -> Uri {
let uri = path_to_uri(path).expect("uri");
self.notify(
DidOpenTextDocument::METHOD,
serde_json::json!({
"textDocument": {
"uri": uri, "languageId": "systemverilog",
"version": 1, "text": text,
}
}),
);
uri
}
fn watched(&mut self, paths: &[PathBuf]) {
let changes: Vec<FileEvent> = paths
.iter()
.map(|path| FileEvent {
uri: path_to_uri(path).expect("uri"),
typ: FileChangeType::CHANGED,
})
.collect();
self.notify(DidChangeWatchedFiles::METHOD, DidChangeWatchedFilesParams { changes });
}
}
/// How many times the index holds a package of this name.
fn indexed(session: &Session, name: &str) -> usize {
session.server.workspace.index().member(name, "K").len()
}
#[test]
fn a_client_that_did_not_ask_is_never_sent_a_registration() {
// Such a client keeps the save-only staleness model, and must not be
// sent a request it has no handler for.
let tree = Tree::new("noregister");
let session = Session::new(vec![tree.path.clone()], false);
assert!(session.requests().is_empty(), "nothing may be asked of it");
}
#[test]
fn a_client_that_asked_is_registered_after_initialized() {
let tree = Tree::new("register");
let session = Session::new(vec![tree.path.clone()], true);
let requests = session.requests();
assert_eq!(requests.len(), 1, "{requests:#?}");
assert_eq!(requests[0].0, RegisterCapability::METHOD);
assert_eq!(
requests[0].1,
serde_json::json!({
"registrations": [{
"id": "vfmt-watched-files-0",
"method": "workspace/didChangeWatchedFiles",
"registerOptions": {
"watchers": [{ "globPattern": "**/*.{v,vh,sv,svh}" }]
},
}]
})
);
}
#[test]
fn a_configured_filelist_is_watched_too() {
let tree = Tree::new("registerfilelist");
tree.package("rtl/a.sv", "a");
tree.write("files.f", "rtl/a.sv\n");
tree.write("vfmt.toml", "filelist = \"files.f\"\n");
let session = Session::new(vec![tree.path.clone()], true);
let requests = session.requests();
let watchers = &requests[0].1["registrations"][0]["registerOptions"]["watchers"];
assert_eq!(
watchers,
&serde_json::json!([
{ "globPattern": "**/*.{v,vh,sv,svh}" },
{ "globPattern": tree.path.join("files.f").to_str().expect("utf-8") },
]),
"the filelist is watched by its own path"
);
}
/// A `vfmt.filelist` push, in the shape a client sends it.
fn filelist_push(path: &str) -> Value {
serde_json::json!({ "settings": { "vfmt": { "filelist": path } } })
}
#[test]
fn a_new_filelist_setting_replaces_the_registration() {
// The watched path is baked into the registration, so the old one must
// go and a new one take its place — otherwise the new filelist is
// exactly the file nobody is watching.
let tree = Tree::new("rewatch");
tree.package("rtl/a.sv", "a");
tree.write("files.f", "rtl/a.sv\n");
tree.write("other.f", "rtl/a.sv\n");
let mut session = Session::new(vec![tree.path.clone()], true);
assert_eq!(session.requests().len(), 1, "the registration made at startup");
session.notify(DidChangeConfiguration::METHOD, filelist_push("files.f"));
let requests = session.requests();
assert_eq!(requests.len(), 2, "{requests:#?}");
assert_eq!(requests[0].0, UnregisterCapability::METHOD);
assert_eq!(requests[0].1["unregisterations"][0]["id"], "vfmt-watched-files-0");
assert_eq!(requests[1].0, RegisterCapability::METHOD);
let registration = &requests[1].1["registrations"][0];
assert_eq!(registration["id"], "vfmt-watched-files-1", "a fresh id");
assert_eq!(
registration["registerOptions"]["watchers"][1]["globPattern"],
tree.path.join("files.f").to_str().expect("utf-8").to_string()
);
// The same value again moves nothing, so nothing is re-registered.
session.notify(DidChangeConfiguration::METHOD, filelist_push("files.f"));
assert!(session.requests().is_empty(), "re-pushing the same path is not a change");
// A different one is.
session.notify(DidChangeConfiguration::METHOD, filelist_push("other.f"));
let requests = session.requests();
assert_eq!(requests.len(), 2, "{requests:#?}");
assert_eq!(requests[0].1["unregisterations"][0]["id"], "vfmt-watched-files-1");
assert_eq!(
requests[1].1["registrations"][0]["registerOptions"]["watchers"][1]["globPattern"],
tree.path.join("other.f").to_str().expect("utf-8").to_string()
);
}
#[test]
fn a_client_that_did_not_ask_is_not_re_registered_either() {
let tree = Tree::new("norewatch");
tree.write("files.f", "\n");
let mut session = Session::new(vec![tree.path.clone()], false);
session.notify(DidChangeConfiguration::METHOD, filelist_push("files.f"));
assert!(session.requests().is_empty());
}
#[test]
fn one_notification_rebuilds_the_index_once_however_many_files_it_names() {
// The `git checkout` shape. Rebuilding per event would re-scan the
// workspace once per changed file for a single answer.
let tree = Tree::new("oncepernotification");
tree.package("rtl/open.sv", "open_pkg");
let mut session = Session::new(vec![tree.path.clone()], true);
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");
for i in 0..40 {
tree.package(&format!("rtl/f{i}.sv"), &format!("p{i}"));
}
let changed: Vec<PathBuf> =
(0..40).map(|i| tree.path.join(format!("rtl/f{i}.sv"))).collect();
session.watched(&changed);
assert_eq!(session.publishes(), 1, "one rebuild for the whole list");
assert_eq!(indexed(&session, "p0"), 1, "and it really did rebuild");
assert_eq!(indexed(&session, "p39"), 1);
}
#[test]
fn a_created_file_reaches_the_index_with_no_save_anywhere() {
let tree = Tree::new("created");
tree.package("rtl/open.sv", "open_pkg");
let mut session = Session::new(vec![tree.path.clone()], true);
session.open(
&tree.path.join("rtl/open.sv"),
"package open_pkg;\n localparam K = 1;\nendpackage\n",
);
assert_eq!(indexed(&session, "pulled"), 0, "premise: not there yet");
tree.package("rtl/pulled.sv", "pulled");
session.watched(&[tree.path.join("rtl/pulled.sv")]);
assert_eq!(indexed(&session, "pulled"), 1, "the `git pull` case");
// ... and a deletion is a change in the other direction.
std::fs::remove_file(tree.path.join("rtl/pulled.sv")).expect("remove");
session.watched(&[tree.path.join("rtl/pulled.sv")]);
assert_eq!(indexed(&session, "pulled"), 0, "the `git checkout` case");
}
#[test]
fn an_event_for_a_file_outside_the_scope_still_rebuilds_but_indexes_nothing() {
// The ladder re-applies during the rebuild, so an unlisted file stays
// unlisted — and one rebuild for a stray in-tree source is cheaper than
// deciding, per event, whether the filelist names it.
let tree = Tree::new("outsidescope");
tree.package("rtl/a.sv", "a");
tree.package("rtl/unlisted.sv", "unlisted");
tree.write("files.f", "rtl/a.sv\n");
tree.write("vfmt.toml", "filelist = \"files.f\"\n");
let mut session = Session::new(vec![tree.path.clone()], true);
assert_eq!(indexed(&session, "unlisted"), 0, "premise: the filelist omits it");
session.watched(&[tree.path.join("rtl/unlisted.sv")]);
assert_eq!(indexed(&session, "a"), 1, "the listed file survives the rebuild");
assert_eq!(indexed(&session, "unlisted"), 0, "and the unlisted one stays out");
}
#[test]
fn an_unrelated_file_event_costs_no_rebuild() {
let tree = Tree::new("stray");
tree.package("rtl/open.sv", "open_pkg");
let mut session = Session::new(vec![tree.path.clone()], true);
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");
session.watched(&[tree.path.join("README.md"), tree.path.join("target/build.log")]);
assert_eq!(session.publishes(), 0, "a stray event is dropped, not re-scanned");
session.notify(
DidChangeWatchedFiles::METHOD,
DidChangeWatchedFilesParams { changes: Vec::new() },
);
assert_eq!(session.publishes(), 0, "and so is an empty notification");
}
#[test]
fn an_open_buffer_still_beats_disk_after_a_watched_file_rebuild() {
// The rule the rebuild has always had, checked on the new path into
// it: an external change must never clobber what the user is looking
// at. Here the file on disk is *also* the open one, rewritten behind
// the editor's back — the buffer still wins.
let tree = Tree::new("overlay");
tree.package("rtl/open.sv", "on_disk");
let path = tree.path.join("rtl/open.sv");
let mut session = Session::new(vec![tree.path.clone()], true);
let uri = session.open(&path, "package in_buffer;\n localparam K = 1;\nendpackage\n");
assert_eq!(indexed(&session, "on_disk"), 1, "premise: indexed from disk at startup");
tree.package("rtl/open.sv", "rewritten_on_disk");
session.watched(std::slice::from_ref(&path));
assert_eq!(indexed(&session, "in_buffer"), 1, "the buffer wins the rebuild");
assert_eq!(indexed(&session, "rewritten_on_disk"), 0, "disk loses");
assert_eq!(indexed(&session, "on_disk"), 0, "and the stale copy is gone");
let doc = session.server.workspace.document(&uri).expect("still open");
assert!(doc.text.contains("in_buffer"), "and the buffer's own text is untouched");
}
#[test]
fn the_uri_helper_and_the_watch_filter_agree_about_the_filelist() {
// `touches_scope` compares paths, and the path it compares against is
// whatever `filelist_path` resolved — a mismatch would silently stop
// filelist edits from rebuilding anything.
let tree = Tree::new("filelistevent");
tree.package("rtl/a.sv", "a");
tree.package("rtl/b.sv", "b");
tree.write("files.f", "rtl/a.sv\n");
tree.write("vfmt.toml", "filelist = \"files.f\"\n");
let mut session = Session::new(vec![tree.path.clone()], true);
session.open(&tree.path.join("rtl/a.sv"), "package a;\n localparam K = 1;\nendpackage\n");
let _ = session.drain();
assert_eq!(indexed(&session, "b"), 0, "premise: not listed yet");
tree.write("files.f", "rtl/a.sv\nrtl/b.sv\n");
session.watched(&[tree.path.join("files.f")]);
assert_eq!(session.publishes(), 1, "the filelist's own edit rebuilds");
assert_eq!(indexed(&session, "b"), 1, "and the newly listed file is in");
}
#[test]
fn a_malformed_watched_files_notification_is_dropped() {
let tree = Tree::new("malformed");
tree.package("rtl/open.sv", "open_pkg");
let mut session = Session::new(vec![tree.path.clone()], true);
session.open(
&tree.path.join("rtl/open.sv"),
"package open_pkg;\n localparam K = 1;\nendpackage\n",
);
let _ = session.drain();
session.notify(DidChangeWatchedFiles::METHOD, serde_json::json!({ "changes": "nonsense" }));
assert_eq!(session.publishes(), 0, "no id to answer on, so nothing happens");
}
#[test]
fn a_non_file_uri_in_an_event_is_ignored() {
let tree = Tree::new("nonfileuri");
tree.package("rtl/open.sv", "open_pkg");
let mut session = Session::new(vec![tree.path.clone()], true);
session.open(
&tree.path.join("rtl/open.sv"),
"package open_pkg;\n localparam K = 1;\nendpackage\n",
);
let _ = session.drain();
let changes = vec![FileEvent {
uri: Uri::from_str("untitled:Untitled-1").expect("uri"),
typ: FileChangeType::CREATED,
}];
session.notify(DidChangeWatchedFiles::METHOD, DidChangeWatchedFilesParams { changes });
assert_eq!(session.publishes(), 0);
}
}
+5 -1
View File
@@ -246,7 +246,11 @@ impl Workspace {
/// The filelist governing this workspace, if any: the client's setting
/// first (absolute, or relative to the first root), else the `filelist`
/// key of the config governing a root, in root order.
fn filelist_path(&self) -> Option<PathBuf> {
///
/// Public because the file watchers must name it: a `.f` edited outside
/// the editor changes the index's scope, and nothing else on disk would
/// tell us (`docs/features/file-watching/README.md`).
pub fn filelist_path(&self) -> Option<PathBuf> {
if let Some(setting) = &self.client.filelist {
let path = Path::new(setting);
return Some(match self.roots.first() {
+266
View File
@@ -0,0 +1,266 @@
//! `workspace/didChangeWatchedFiles`: the index's answer to changes vfmt never
//! saw an editor make.
//!
//! Until this, the index was rebuilt on save and (with no workspace root) on
//! open — so a `git pull`, a branch checkout, a generated file, or an edit to
//! the `.f` filelist itself stayed invisible until the user happened to save
//! something. The client already watches the disk for its own reasons; this
//! module asks it to say what it sees. See
//! `docs/features/file-watching/README.md`.
use std::path::Path;
use lsp_types::notification::{DidChangeWatchedFiles, Notification as _};
use lsp_types::{
DidChangeWatchedFilesRegistrationOptions, FileEvent, FileSystemWatcher, GlobPattern,
InitializeParams, Registration, Unregistration,
};
use vfmt_core::walk::EXTENSIONS;
use crate::uri::uri_to_path;
/// Every source file the workspace walk would take, in one glob.
///
/// Deliberately the same four extensions as `vfmt_core::walk::EXTENSIONS` and
/// nothing else: a watcher wide enough to cover a build directory or a
/// `target/` tree would hand us thousands of events that cannot change the
/// index. `pinned_to_the_extensions_the_walk_takes` asserts the two agree.
pub const SOURCE_GLOB: &str = "**/*.{v,vh,sv,svh}";
/// Whether the client can be asked to watch files at all.
///
/// The protocol has no static form of this capability — a server that wants
/// file events must register for them, and a client that did not advertise
/// dynamic registration cannot be asked. Such a client simply keeps the
/// save-only staleness model it had before this feature.
pub fn dynamic_registration(params: &InitializeParams) -> bool {
params
.capabilities
.workspace
.as_ref()
.and_then(|workspace| workspace.did_change_watched_files.as_ref())
.and_then(|watched| watched.dynamic_registration)
.unwrap_or(false)
}
/// The registration to send as `client/registerCapability`: the source glob,
/// plus the configured filelist's own path when there is one.
///
/// `serial` numbers the registration so a later one can unregister it by name;
/// a re-registration is what a change of `vfmt.filelist` needs, because the
/// path being watched is part of the registration itself.
///
/// No `kind` is set on either watcher, which the protocol defines as
/// create|change|delete — all three matter here, since a file appearing and a
/// file vanishing move the index exactly as much as one being rewritten.
pub fn registration(serial: u32, filelist: Option<&Path>) -> Registration {
let options = DidChangeWatchedFilesRegistrationOptions { watchers: watchers(filelist) };
Registration {
id: registration_id(serial),
method: DidChangeWatchedFiles::METHOD.to_string(),
// Cannot fail for this shape (no non-string map keys, no floats), and
// a `None` here would register a watcher for nothing rather than
// corrupt anything — so there is nothing to report and nobody to
// report it to.
register_options: serde_json::to_value(options).ok(),
}
}
/// Undo a previous `registration`, by the id it carried.
pub fn unregistration(id: String) -> Unregistration {
Unregistration { id, method: DidChangeWatchedFiles::METHOD.to_string() }
}
/// The watchers a registration carries: sources always, the filelist when the
/// project has one.
///
/// The filelist is watched by its own absolute path rather than by a `*.f`
/// glob: a filelist can be called anything (`files.list`, `srcs.txt`), and a
/// glob wide enough for every name would also fire on every unrelated `.f` in
/// the tree. A path that is not valid UTF-8 cannot be written as a glob and is
/// simply not watched — the same restriction `uri.rs` already lives under.
fn watchers(filelist: Option<&Path>) -> Vec<FileSystemWatcher> {
let mut watchers = vec![watcher(SOURCE_GLOB.to_string())];
if let Some(pattern) = filelist.and_then(|path| path.to_str()) {
watchers.push(watcher(pattern.to_string()));
}
watchers
}
fn watcher(pattern: String) -> FileSystemWatcher {
FileSystemWatcher { glob_pattern: GlobPattern::String(pattern), kind: None }
}
fn registration_id(serial: u32) -> String {
format!("vfmt-watched-files-{serial}")
}
/// Whether a notification's events touch anything the index reads.
///
/// Asked **once per notification**, not once per file: a branch checkout
/// arrives as one notification carrying hundreds of events, and rebuilding per
/// event would re-scan the workspace hundreds of times for one answer.
///
/// The client's globs already filter, but a client is free to send more than
/// it was asked for (some watch a whole workspace and forward everything), and
/// a stray `.txt` must not cost a workspace re-scan.
pub fn touches_scope(changes: &[FileEvent], filelist: Option<&Path>) -> bool {
changes
.iter()
.filter_map(|change| uri_to_path(&change.uri))
.any(|path| watched(&path, filelist))
}
fn watched(path: &Path, filelist: Option<&Path>) -> bool {
if filelist == Some(path) {
return true;
}
let extension = path.extension().and_then(|e| e.to_str()).unwrap_or_default();
EXTENSIONS.contains(&extension)
}
#[cfg(test)]
mod tests {
use super::*;
use lsp_types::{
ClientCapabilities, DidChangeWatchedFilesClientCapabilities, FileChangeType, Uri,
WorkspaceClientCapabilities,
};
use std::path::PathBuf;
use std::str::FromStr;
fn saying(dynamic_registration: Option<bool>) -> InitializeParams {
InitializeParams {
capabilities: ClientCapabilities {
workspace: Some(WorkspaceClientCapabilities {
did_change_watched_files: Some(DidChangeWatchedFilesClientCapabilities {
dynamic_registration,
relative_pattern_support: None,
}),
..Default::default()
}),
..Default::default()
},
..Default::default()
}
}
#[test]
fn only_a_client_that_says_so_is_asked_to_watch() {
assert!(!dynamic_registration(&InitializeParams::default()), "silence means no");
assert!(!dynamic_registration(&saying(None)), "an empty capability means no");
assert!(!dynamic_registration(&saying(Some(false))));
assert!(dynamic_registration(&saying(Some(true))));
}
#[test]
fn the_registration_is_the_shape_the_protocol_asks_for() {
// Pinned as JSON, because this is what goes on the wire and a client
// that cannot read it watches nothing at all — silently.
let value = serde_json::to_value(registration(0, None)).expect("json");
assert_eq!(
value,
serde_json::json!({
"id": "vfmt-watched-files-0",
"method": "workspace/didChangeWatchedFiles",
"registerOptions": { "watchers": [{ "globPattern": "**/*.{v,vh,sv,svh}" }] },
})
);
}
#[test]
fn a_configured_filelist_is_watched_by_its_own_path() {
let value =
serde_json::to_value(registration(2, Some(Path::new("/p/files.f")))).expect("json");
assert_eq!(
value,
serde_json::json!({
"id": "vfmt-watched-files-2",
"method": "workspace/didChangeWatchedFiles",
"registerOptions": { "watchers": [
{ "globPattern": "**/*.{v,vh,sv,svh}" },
{ "globPattern": "/p/files.f" },
] },
})
);
}
#[test]
fn no_filelist_means_no_second_watcher() {
assert_eq!(watchers(None).len(), 1, "sources only");
assert_eq!(watchers(Some(Path::new("/p/files.f"))).len(), 2, "and the filelist");
}
#[test]
fn an_unregistration_names_the_same_id_and_method() {
let registration = registration(7, None);
let undo = unregistration(registration.id.clone());
assert_eq!(undo.id, "vfmt-watched-files-7");
assert_eq!(undo.method, registration.method);
}
#[test]
fn the_glob_is_pinned_to_the_extensions_the_walk_takes() {
// A file the walk indexes but the glob does not name is a file whose
// external changes are invisible; the reverse is wasted rebuilds.
for extension in EXTENSIONS {
assert!(
SOURCE_GLOB.contains(&format!("{extension},"))
|| SOURCE_GLOB.contains(&format!("{extension}}}")),
"{extension} is not in {SOURCE_GLOB}"
);
}
assert_eq!(EXTENSIONS.len(), 4, "a fifth extension needs a wider glob");
}
fn event(path: &str) -> FileEvent {
FileEvent {
uri: Uri::from_str(&format!("file://{path}")).expect("uri"),
typ: FileChangeType::CHANGED,
}
}
#[test]
fn a_source_file_event_asks_for_a_rebuild() {
for name in ["/p/a.sv", "/p/a.v", "/p/a.svh", "/p/a.vh"] {
assert!(touches_scope(&[event(name)], None), "{name}");
}
}
#[test]
fn an_unrelated_extension_does_not() {
// The stray-event case: a client that forwards more than it was asked
// for must not cost a workspace re-scan per keystroke in a README.
assert!(!touches_scope(&[event("/p/notes.txt")], None));
assert!(!touches_scope(&[event("/p/target/build.log")], None));
assert!(!touches_scope(&[event("/p/files.f")], None), "an unconfigured filelist");
assert!(!touches_scope(&[], None), "and an empty notification");
}
#[test]
fn the_configured_filelist_asks_for_a_rebuild() {
let filelist = PathBuf::from("/p/files.f");
assert!(touches_scope(&[event("/p/files.f")], Some(&filelist)));
assert!(!touches_scope(&[event("/p/other.f")], Some(&filelist)), "not another one");
}
#[test]
fn one_relevant_event_among_many_is_enough() {
// The `git checkout` shape: one notification, a long list, one answer.
let mut changes: Vec<FileEvent> =
(0..200).map(|i| event(&format!("/p/n{i}.txt"))).collect();
assert!(!touches_scope(&changes, None));
changes.push(event("/p/rtl/top.sv"));
assert!(touches_scope(&changes, None));
}
#[test]
fn a_non_file_uri_is_ignored_rather_than_guessed_at() {
let event = FileEvent {
uri: Uri::from_str("untitled:Untitled-1").expect("uri"),
typ: FileChangeType::CREATED,
};
assert!(!touches_scope(&[event], None));
}
}
+185 -21
View File
@@ -23,32 +23,32 @@ fn frame(payload: &str) -> String {
/// Split a stdout dump into its JSON payloads.
fn unframe(mut input: impl BufRead) -> Vec<serde_json::Value> {
let mut out = Vec::new();
while let Some(message) = read_message(&mut input) {
out.push(message);
}
out
}
/// One framed message, or `None` when the stream ends or goes wrong.
fn read_message(input: &mut impl BufRead) -> Option<serde_json::Value> {
let mut length = None;
// Headers, terminated by an empty line.
loop {
let mut length = None;
// Headers, terminated by an empty line.
loop {
let mut line = String::new();
if input.read_line(&mut line).unwrap_or(0) == 0 {
return out;
}
let trimmed = line.trim_end_matches(['\r', '\n']);
if trimmed.is_empty() {
break;
}
if let Some(value) = trimmed.strip_prefix("Content-Length: ") {
length = value.parse::<usize>().ok();
}
let mut line = String::new();
if input.read_line(&mut line).unwrap_or(0) == 0 {
return None;
}
let Some(length) = length else { return out };
let mut body = vec![0u8; length];
if input.read_exact(&mut body).is_err() {
return out;
let trimmed = line.trim_end_matches(['\r', '\n']);
if trimmed.is_empty() {
break;
}
match serde_json::from_slice(&body) {
Ok(value) => out.push(value),
Err(_) => return out,
if let Some(value) = trimmed.strip_prefix("Content-Length: ") {
length = value.parse::<usize>().ok();
}
}
let mut body = vec![0u8; length?];
input.read_exact(&mut body).ok()?;
serde_json::from_slice(&body).ok()
}
fn temp_dir(name: &str) -> PathBuf {
@@ -1699,3 +1699,167 @@ fn inlay_hints_round_trip_over_the_wire() {
let _ = std::fs::remove_dir_all(&dir);
}
/// A live session: unlike `talk`, one message goes out at a time and the
/// answers are read as they arrive.
///
/// That is what lets a test change the *disk* mid-session and know the server
/// has not looked yet — `talk` writes the whole script up front, so anything
/// it does to the filesystem afterwards races the server.
struct Live {
child: std::process::Child,
stdin: std::process::ChildStdin,
stdout: BufReader<std::process::ChildStdout>,
}
impl Live {
fn start() -> Live {
let mut child = Command::new(env!("CARGO_BIN_EXE_vfmt-server"))
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.expect("the server binary starts");
let stdin = child.stdin.take().expect("stdin");
let stdout = BufReader::new(child.stdout.take().expect("stdout"));
Live { child, stdin, stdout }
}
fn send(&mut self, payload: &str) {
self.stdin.write_all(frame(payload).as_bytes()).expect("write");
self.stdin.flush().expect("flush");
}
/// Read until a message the predicate accepts, and return it.
///
/// Capped rather than unbounded: a test that hangs forever waiting for a
/// message the server will never send is far worse to debug than one that
/// fails with the transcript.
fn wait_for(&mut self, wanted: impl Fn(&serde_json::Value) -> bool) -> serde_json::Value {
let mut seen = Vec::new();
for _ in 0..500 {
let Some(message) = read_message(&mut self.stdout) else { break };
if wanted(&message) {
return message;
}
seen.push(message);
}
panic!("the server never said what was waited for; it said {seen:#?}");
}
fn finish(mut self) {
self.send(r#"{"jsonrpc":"2.0","id":99,"method":"shutdown","params":null}"#);
self.wait_for(|m| m["id"] == 99);
self.send(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#);
drop(self.stdin);
let status = self.child.wait().expect("the server exits");
assert!(status.success(), "clean exit, got {status:?}");
}
}
#[test]
fn a_file_created_mid_session_is_indexed_through_a_watched_files_notification() {
// The whole feature, end to end and over the wire: a client that says it
// can watch files is *asked* to, a file appears on disk that no editor
// ever opened or saved, one notification says so, and the very next
// `workspace/symbol` finds what is inside it.
let dir = temp_dir("watchedfiles");
let open = dir.join("top.sv");
std::fs::write(&open, "package top_pkg;\n localparam K = 1;\nendpackage\n").expect("write");
let root = format!("file://{}", dir.display());
let open_uri = format!("file://{}", open.display());
let pulled = dir.join("pulled.sv");
let pulled_uri = format!("file://{}", pulled.display());
let query = |id: u32, name: &str| {
format!(
r#"{{"jsonrpc":"2.0","id":{id},"method":"workspace/symbol","params":{{"query":"{name}"}}}}"#
)
};
let mut live = Live::start();
live.send(&format!(
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{"workspace":{{"didChangeWatchedFiles":{{"dynamicRegistration":true}}}}}}}}}}"#
));
live.wait_for(|m| m["id"] == 1);
live.send(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#);
// The registration itself: without it a real client watches nothing, and
// every assertion below would be about a notification no editor sends.
let registration = live.wait_for(|m| m["method"] == "client/registerCapability");
let registered = &registration["params"]["registrations"][0];
assert_eq!(registered["method"], "workspace/didChangeWatchedFiles", "{registration:#?}");
assert_eq!(
registered["registerOptions"]["watchers"],
serde_json::json!([{ "globPattern": "**/*.{v,vh,sv,svh}" }]),
"{registration:#?}"
);
// Answer it the way a real client does. Nothing depends on the answer;
// this proves the server tolerates one arriving mid-session.
let id = serde_json::to_string(&registration["id"]).expect("json");
live.send(&format!(r#"{{"jsonrpc":"2.0","id":{id},"result":null}}"#));
// An open buffer, so the republish half of the rebuild has somewhere to
// land — and so the "no save anywhere" claim has a buffer to not save.
live.send(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{open_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string("package top_pkg;\n localparam K = 1;\nendpackage\n")
.expect("json")
));
live.send(&query(2, "pulled_pkg"));
let before = live.wait_for(|m| m["id"] == 2);
assert_eq!(before["result"].as_array().map(|a| a.len()), Some(0), "premise: not on disk yet");
// The `git pull`: a file appears, and nothing in the editor knows.
std::fs::write(&pulled, "package pulled_pkg;\n localparam K = 1;\nendpackage\n")
.expect("write");
live.send(&format!(
r#"{{"jsonrpc":"2.0","method":"workspace/didChangeWatchedFiles","params":{{"changes":[{{"uri":"{pulled_uri}","type":1}}]}}}}"#
));
live.send(&query(3, "pulled_pkg"));
let after = live.wait_for(|m| m["id"] == 3);
let hits = after["result"].as_array().expect("a symbol list");
assert_eq!(hits.len(), 1, "the created file is in the index: {after:#?}");
assert_eq!(hits[0]["location"]["uri"], pulled_uri.as_str(), "{after:#?}");
// ... and the deletion half, on the same path.
std::fs::remove_file(&pulled).expect("remove");
live.send(&format!(
r#"{{"jsonrpc":"2.0","method":"workspace/didChangeWatchedFiles","params":{{"changes":[{{"uri":"{pulled_uri}","type":3}}]}}}}"#
));
live.send(&query(4, "pulled_pkg"));
let gone = live.wait_for(|m| m["id"] == 4);
assert_eq!(gone["result"].as_array().map(|a| a.len()), Some(0), "{gone:#?}");
live.finish();
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_client_that_cannot_watch_files_is_never_asked_to() {
// The other half of the guard: every existing client — `smoke.js` and
// every other session in this file — sends `capabilities: {}`, and must
// still see nothing but answers to what it asked.
let dir = temp_dir("nowatch");
std::fs::write(dir.join("m.sv"), UNFORMATTED).expect("write");
let root = format!("file://{}", dir.display());
let session = [
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(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
]
.concat();
let messages = talk(&session);
assert!(
!messages.iter().any(|m| m["method"] == "client/registerCapability"),
"a client that did not advertise dynamic registration must not be asked: {messages:#?}"
);
let _ = std::fs::remove_dir_all(&dir);
}
+395
View File
@@ -0,0 +1,395 @@
# file-watching
## Goal
Teach the server about changes it never saw an editor make. Until M9 the
workspace index was rebuilt on `didSave` and — with no workspace root — on
`didOpen`, so a `git pull`, a branch checkout, a file written by a generator,
or an edit to the `.f` filelist itself stayed invisible until the user
happened to save something. Cross-file answers (`definition`, `workspace/symbol`,
hover's define fallback, completion candidates) were then quietly answering
about a tree that no longer existed. LSP already has the mechanism: the client
watches the disk for its own reasons, and `workspace/didChangeWatchedFiles`
lets a server ask to be told. M9 registers for it and rebuilds the index once
per notification.
## Assumptions
- **Registration is the only way in.** The protocol has no static
`didChangeWatchedFiles` server capability — a server that wants file events
must ask for them with `client/registerCapability`, and only a client that
advertised `workspace.didChangeWatchedFiles.dynamicRegistration` can be
asked. A client that did not (VS Code's `vscode-languageclient` and
Neovim's built-in client both do; `editors/vscode/smoke.js` deliberately
sends `capabilities: {}`) keeps exactly the save-only model it had before.
That is the honest remaining staleness window, and it is stated in
`docs/features/vfmt-server/README.md` as well as here.
- **The registration is sent from `Server::new`, not from an `initialized`
handler.** `lsp-server`'s `initialize_finish` *consumes* the client's
`initialized` notification before returning, so the request loop never sees
one. `main` builds the `Server` immediately after `initialize_finish`, which
is precisely the first moment the protocol allows a `client/registerCapability`
— so that is where it goes. A handler on `Initialized::METHOD` would be dead
code that looks alive, which is worse than no handler at all.
- **The answer to the registration is ignored.** A client that refuses (or
answers with an error) simply keeps the save-only model; there is nothing
useful to do with the response and nothing to tell the user that their own
editor's log does not already say.
- **One rebuild per notification, never one per file.** `DidChangeWatchedFilesParams`
carries a *list*, and a branch checkout fills it. The handler asks one
question of the whole list and rebuilds at most once. There is **no
time-based debouncing**: that needs a timer, the server is single-threaded
and synchronous by design (`docs/features/vfmt-server/README.md`), and
adding a thread to save part of a 0.7 s corpus rebuild is not a trade worth
making. A burst of several notifications therefore costs several rebuilds;
in practice VS Code and Neovim both coalesce a checkout into very few.
- **Events are filtered by extension, cheaply.** The registered globs already
filter client-side, but a client is free to forward more than it was asked
for, so `touches_scope` drops a notification whose every path is neither a
source extension (`vfmt_core::walk::EXTENSIONS`) nor the configured
filelist. It does **not** try to decide whether a source file is *in* the
current scope: the scope ladder re-applies during the rebuild anyway, and
one rebuild for a stray in-tree `.sv` is much cheaper than duplicating the
ladder's logic per event and getting it subtly wrong.
- **Only the root filelist is watched, not its nested `-f` targets.**
`vfmt_core::filelist::Filelist` reports the files a filelist names but not
the filelists it *read*, and adding that field is a change to another
module for one caller. So editing a nested `.f` outside the editor is still
invisible until the next save or root-filelist touch. Saving a nested
filelist from inside the editor works today (`didSave` rebuilds), which is
the overwhelmingly common case.
- **The filelist is watched by its absolute path, not by a `*.f` glob.** A
filelist can be called anything (`files.list`, `srcs.txt`), so a glob wide
enough for every name would also fire on every unrelated `.f` in the tree.
A path that is not valid UTF-8 cannot be written as a glob and is simply not
watched — the same restriction `uri.rs` already lives under.
- **`vfmt.toml` itself is not watched.** Its `exclude` and `filelist` keys do
change the index's scope, so editing one outside the editor is still
invisible until the next save — but it is read afresh on every rebuild, so
the very next rebuild from any cause picks it up, and saving it from inside
the editor already rebuilds. Watching it would mean a third watcher and a
second re-registration trigger for a file people edit once a quarter.
- **A changed `vfmt.filelist` re-registers.** The watched path is *inside* the
registration, so a new path needs a new registration: the old one is
unregistered by id and a fresh one sent. The alternative — a static watcher
wide enough that no re-registration is ever needed — would mean watching
every file in the tree, which is exactly the noise the tight globs exist to
avoid.
- **`kind` is left unset on both watchers**, which the protocol defines as
create|change|delete. All three matter: a file appearing and a file
vanishing move the index exactly as much as one being rewritten.
- **A watched-file rebuild cannot clobber an open buffer.** `collect_sources`
overlays every open document's text over the disk copy, and the watched-file
path goes through the same `rebuild_index`. Pinned by a test that rewrites
the open file on disk behind the editor's back.
## Handshakes
### `vfmt_server::watch` (new module)
```rust
pub const SOURCE_GLOB: &str = "**/*.{v,vh,sv,svh}";
pub fn dynamic_registration(params: &InitializeParams) -> bool;
pub fn registration(serial: u32, filelist: Option<&Path>) -> Registration;
pub fn unregistration(id: String) -> Unregistration;
pub fn touches_scope(changes: &[FileEvent], filelist: Option<&Path>) -> bool;
```
`SOURCE_GLOB` is pinned to `vfmt_core::walk::EXTENSIONS` by a test: a file the
walk indexes but the glob does not name is a file whose external changes are
invisible, and the reverse is wasted rebuilds.
### `vfmt_server::server`
- `Server::new` now takes a `ClientAbilities { snippets, file_watching }`
instead of a bare `snippets: bool` — two adjacent bools at a call site is a
bug waiting to happen. `main.rs` fills both from `InitializeParams`.
- `Server::new` sends the `client/registerCapability` request when
`file_watching` is set (see Assumptions for why it is not an `initialized`
handler).
- `workspace/didChangeWatchedFiles` joins `didSave` and the
`exclude`/`filelist` settings change as a caller of the existing `reindex()`
— same rebuild, same "first warning shown, all of them logged" scope
reporting.
- `workspace/didChangeConfiguration` re-registers the watchers when the
resolved filelist path changed.
- Outgoing request ids are `vfmt-<n>`; registration ids are
`vfmt-watched-files-<n>`. Responses to them are ignored in `run`.
### `vfmt_server::state`
`Workspace::filelist_path()` is now **public** (it was private). It is what
the watcher registration names and what `touches_scope` compares against; the
two must be the same path or filelist edits silently stop rebuilding
anything. No behaviour change.
### `editors/*`
**No editor change is needed.** `vscode-languageclient` advertises
`didChangeWatchedFiles.dynamicRegistration` on its own and creates the
`FileSystemWatcher`s from the registration, and Neovim's built-in client does
the same — so both existing setups gain this with no configuration. There is
no new setting.
## Status / TODO
- [x] `crates/vfmt_server/src/watch.rs`: capability probe, registration and
unregistration builders, per-notification event filter
- [x] `client/registerCapability` sent after the handshake, guarded on the
client capability
- [x] `workspace/didChangeWatchedFiles` handled: one `reindex()` per
notification, warnings surfaced exactly as on save
- [x] Filelist watched by path when one is configured; re-registered when
`vfmt.filelist` resolves somewhere else
- [x] `Workspace::filelist_path` made public for the two callers above
- [x] Unit tests (11 in `watch.rs`, 13 in `server.rs` driving a real `Server`
over `Connection::memory()`), 2 new e2e stdio sessions
- [x] `cargo fmt`, `cargo clippy --all-targets`, `cargo test --workspace`,
`node editors/vscode/smoke.js` — all clean
- [ ] Not done, deliberately: no time-based debouncing (needs a timer and a
thread; per-notification coalescing only — see Assumptions).
- [ ] Not done, deliberately: nested `-f` filelists are not watched (needs a
new field on `vfmt_core::filelist::Filelist` — see Assumptions).
- [ ] Not done, deliberately: no `workspace/didChangeWorkspaceFolders`. Adding
or removing a folder mid-session still needs a restart; that is its own
change, with its own question about re-registering the watchers.
## Work log
### 2026-08-24 — dev agent, M9
Built in the order the brief lists: the pure `watch` module first, then the
wiring, then the tests, then the docs. Decisions worth recording:
- **Registration moved out of an `initialized` handler.** The first version
hung the registration off `Initialized::METHOD` in `server.rs`'s
notification match, which is what the protocol suggests. The e2e session
then blocked forever waiting for a registration request that never came:
`lsp-server`'s `initialize_finish` receives and swallows the `initialized`
notification itself, so the request loop never sees one. Moved into
`Server::new`, which `main` calls immediately after `initialize_finish` —
the same instant, and provably reached. Recorded in Assumptions because it
is exactly the kind of dead-but-plausible handler a reader would re-add.
- **`ClientAbilities` instead of a second `bool` parameter.**
`Server::new(conn, roots, true, false)` is a call site nobody can read.
- **Two counters, not one.** Registration ids and outgoing request ids are
different namespaces; sharing one counter made the ids jump (`-0`, then
`-3`) for no reason a reader could reconstruct.
- **`touches_scope` filters by extension only, not by scope membership.**
Deciding per event whether the filelist names a file would duplicate the
scope ladder outside `state.rs`, where it would drift. The ladder re-applies
during the rebuild, so an out-of-scope source file costs one rebuild and
changes nothing — pinned by
`an_event_for_a_file_outside_the_scope_still_rebuilds_but_indexes_nothing`.
- **The e2e test needed a new harness.** `talk()` writes the whole session up
front and reads afterwards, so anything a test does to the *filesystem*
mid-script races the server. Added `Live` next to it: one message at a time,
answers read as they arrive, so the test can create a file on disk knowing
the server has not looked yet. `wait_for` is capped at 500 messages and
panics with the transcript rather than hanging a CI job forever. `unframe`
was split into a reusable `read_message` for it; no behaviour change to the
existing tests.
**Files touched outside this feature's module**, all minimal:
- `crates/vfmt_server/src/state.rs` — `filelist_path` private → public, with
a doc comment saying why. No logic change.
- `crates/vfmt_server/src/main.rs` — `mod watch;`, and `ClientAbilities` at
the `Server::new` call site.
- `crates/vfmt_server/tests/e2e.rs` — the `Live` harness and the
`unframe`/`read_message` split, plus the two new sessions.
**Not touched, per the brief**: `TODO.md` §8's M9 checkbox and the umbrella
plan's checklist are left for the lead. `editors/vscode/smoke.js` is
untouched and still passes unchanged — it sends `capabilities: {}`, so it is
never asked to register anything, which
`a_client_that_cannot_watch_files_is_never_asked_to` pins as a test rather
than as a hope. No version bump, no CHANGELOG entry, no new dependency, no
threads.
**Verification.** `cargo fmt --all -- --check` clean; `cargo clippy
--all-targets` silent; `cargo test --workspace` green. `vfmt_server` went
from 372 to 396 unit tests (+24: 11 in `watch.rs`, 13 in `server.rs`) and
from 19 to 21 e2e sessions (+2). `node editors/vscode/smoke.js
target/debug/vfmt-server` → OK, 8 messages, unchanged.
## QA log
### 2026-08-24 — QA agent, M9
**Gates.** `cargo fmt --all -- --check` clean. `cargo clippy --all-targets`
silent. `cargo test -p vfmt_server`: **394 passed + 2 ignored (= 396 unit) +
21 e2e + 3 grammar**, matching the Work log's counts exactly. `cargo test
--workspace`: green, no failures anywhere. `node editors/vscode/smoke.js
target/debug/vfmt-server` → OK, 8 messages, unchanged (capabilities `{}` →
never registered, confirmed both by the new
`a_client_that_cannot_watch_files_is_never_asked_to` e2e test and by running
smoke.js itself). No `unwrap`/`expect`/`panic!` outside `#[cfg(test)]` in
`watch.rs` or the `server.rs` diff; no `unsafe` added. `TODO.md` and the
umbrella `README.md` confirmed untouched (`git status`/`git diff --stat`),
per the QA brief's own scope restriction.
**The `initialize_finish` claim, independently verified against the vendored
source**, not taken on the dev's word: `~/.cargo/registry/.../lsp-server-0.10.0/src/lib.rs:194-208`.
`initialize_finish` sends the `InitializeResult` response and then calls
`self.receiver.recv()` directly (not through the `Connection`'s public
message loop) — if that message is the `initialized` notification it returns
`Ok(())` and the message is gone; it is never pushed anywhere `run()`'s
`self.connection.receiver.recv()` loop could see it. A handler on
`Initialized::METHOD` inside that loop is therefore provably unreachable in
the normal handshake, confirming the Assumptions section's claim and the
non-obvious choice to register from `Server::new`. (A client that sends
something *other* than `initialized` as its very next message makes
`initialize_finish` return `Err`, which `main`'s `?` propagates before
`Server::new` is ever called — pre-existing behavior, not a new race this
feature introduces.)
**Adversarial testing, real `target/release/vfmt-server` binary over stdio**
(hand-rolled Python framing client, one message at a time — the same
write-then-wait-for-reply shape `tests/e2e.rs`'s `Live` harness uses, not a
threaded reader, per the prior QA note about that class of harness hang).
Scripts are in the scratchpad, not the repo. All of the following **PASS**:
- **Percent-encoded spaces, end to end.** A workspace root
`/tmp/Clock Divider .../`, plus a *file* also named with a space
(`clock divider top.sv`), created after the session starts. The
`client/registerCapability` round-trips over a space-containing root, a
`workspace/didChangeWatchedFiles` `Created` event for the space-containing
path indexes it, and `workspace/symbol` finds it on the very next query
with the location URI round-tripping back to the same path. This is
`uri_to_path`'s existing percent-decoding
(`crates/vfmt_server/src/uri.rs:36-53`) doing exactly what it already did
for `didOpen`/`hover`/etc — `watch::touches_scope` and the reindex path
route every event through the same helper, so there was no new surface for
this to go wrong on, and none did.
- **Burst behavior, measured on the real 860-file corpus** (`corpus/`,
read-only, untouched). `client/registerCapability` on that root completes
in 0.34 s. One relevant `didChangeWatchedFiles` notification to the next
answered request: **0.32 s**. Three back-to-back notifications (the `git
checkout` shape) to the next answered request: **0.98 s** — almost exactly
3×, confirming the "no debounce, one rebuild per notification" model costs
what the README says it costs, not more. The server answered a *correct*
follow-up query (`workspace/symbol("clk")`, non-empty, right after the
burst) every time — never wedged, never stale past the burst. This is
faster than the vfmt-server README's own 0.68 s/rebuild debug-build
baseline (release build, as expected) — the honest-gaps assessment below
updates the number for a release binary.
- **Delete the open file.** Deleted the file backing an open buffer on disk,
then sent the matching `Deleted` watched-files event: the symbol it
defines stayed in `workspace/symbol` (buffer overlay wins, per
`an_open_buffer_still_beats_disk_after_a_watched_file_rebuild` and
`collect_sources`'s "contribute themselves when they are not on disk"
rule). Closed the buffer and re-sent the same `Deleted` event: the symbol
disappeared cleanly, no stale location, no crash on the follow-up query.
- **Delete a file that another file references.** Same shape: definer
removed, referencer's `workspace/symbol` query still answers (empty for
the deleted symbol), no crash.
- **`didChangeWatchedFiles` before any `didOpen`.** Sent straight after the
registration handshake, zero open buffers: no panic, and the created file
is indexed on the next `workspace/symbol` query. The "no shared mutable
state, no locks" design (`docs/features/vfmt-server/README.md`) leaves
nothing that startup ordering could race here, and the run confirms it.
- **Filelist emptied.** Rewrote the configured filelist to zero bytes, sent
the matching `Changed` event: the index shrinks to what the now-empty
filelist names (nothing), no crash — this **is** the "filelist names
exactly the set of files" contract working correctly, not a fallback case
(an empty filelist is a valid, if odd, filelist).
- **Filelist deleted.** Removed the filelist file itself, sent the matching
`Deleted` event on the filelist's own watched path: falls back to the
workspace walk (the previously-filelist-scoped symbol reappears) with a
`window/showMessage` warning surfaced — confirms `source_files`'s
`Err(problem)` branch (`state.rs`) is reached correctly from the
watched-files path, not just from `didSave`.
- **Warning volume on a multi-warning filelist, through the watched-files
path specifically** (not just `didSave`, which the filelist feature's own
QA already covered): a filelist with an unsupported flag and three missing
files, touched via a watched-files event, produced **exactly one**
`window/showMessage` ("... and 4 more — see the vfmt log") and **five**
`window/logMessage`s — the "first warning shown, all of them logged" rule
holds on this new trigger, not just the old ones.
- **Re-registration.** Changed `vfmt.filelist` three times in a row: to a
path containing a space (watched verbatim, not escaped or broken — the
glob pattern is a literal path string, not a real glob, so a raw space is
correct), to a nonexistent path (still unregisters/re-registers cleanly,
still answers requests afterward via the workspace-walk fallback), and
back to the same value as immediately before (no re-registration at all —
`set_client_settings`'s equality check holds). Registration ids across all
three changes were `vfmt-watched-files-0/1/2/3` in strict sequence, never
repeated, and each `client/unregisterCapability` named exactly the id the
registration immediately before it carried — confirmed against the wire
messages, not just the unit tests already pinning this in `server.rs`.
- **A client that answers `client/registerCapability` with a JSON-RPC
error** (not just an ignored `result: null`): no crash, no retry loop (no
second registration request arrived in a 1.5 s window), and the server
answered a normal request correctly afterward. `Message::Response(_) => {}`
in `run()` (`server.rs`) matches on the `Message::Response` variant alone,
before ever looking at whether the JSON carries `result` or `error`, so an
error response is exactly as inert as a success — confirmed both by
reading the match arm and by driving a real error response at the binary.
- **Malformed / non-file URIs.** A notification whose `changes` mixed a
string that isn't a URI at all, an empty string, a scheme-less relative
path (`rtl/a.sv`), and an `http://` URI: zero `publishDiagnostics`
republishes followed (i.e., zero rebuilds), and the server stayed correct
and responsive afterward. `uri_to_path`'s `strip_prefix("file://")` on a
non-`file:` or malformed string returns `None`, and `touches_scope`'s
`filter_map` drops it before the `.any(...)` ever runs — verified on the
real binary, not just `an_a_non_file_uri_is_ignored_rather_than_guessed_at`'s
unit-level check with one well-formed `untitled:` URI.
**No blocking findings.** Every claim in the feature README and the dev's
Work log checks out against the real binary, not only its own test suite.
**Honest-gaps assessment (item 4 of the brief).** All three disclosed gaps
are stated where a user/maintainer would actually look — the feature
README's own Assumptions *and* Status/TODO, and restated in
`docs/features/vfmt-server/README.md`'s "State and staleness" section (the
file most likely to be read for "why is my index stale"):
- **No debounce.** Measured above: 3×~0.32 s ≈ 0.98 s for a burst on the full
860-file corpus in a release build. That is well inside "the user won't
notice a beat" territory for the realistic case (a checkout that touches a
fraction of the tree coalesces into very few notifications per the
README's own claim about VS Code/Neovim); the pathological case — every
file in a checkout arriving as its own separate notification — was not
reproduced (both editors' watcher implementations coalesce, and simulating
a non-coalescing client would be testing a hypothetical client, not this
one), but the linear cost model documented ("a burst … costs several
rebuilds") is exactly what was measured, no worse. Acceptable as shipped.
- **Nested `-f` filelists unwatched, and `vfmt.toml` unwatched.** Read-only
confirmed against the Assumptions section's own reasoning (the missing
`Filelist`-reads-filelists field, and "re-read every rebuild" respectively)
— both are stated, reasoned, and cheap to work around (save inside the
editor). Not independently re-tested beyond reading the code path, since
the dev's reasoning is sound and nothing about the watched-files feature
changes it.
- **Static-watcher / non-dynamic-registration clients.** Confirmed via
`a_client_that_cannot_watch_files_is_never_asked_to` (repo test) and
independently via the malformed-URI/error-response probes above using
`capabilities: {}` implicitly (no registration ever requested in any
session that didn't advertise the capability) — such a client keeps
exactly the pre-M9 save-only model, stated in both feature READMEs.
**Verdict: ship.** All dev claims verified, including the two claims a QA
pass exists specifically to not take on faith (the `initialize_finish`
source-level justification, and the burst-cost number). The percent-encoded
space path — this session's specific concern about the user's own directory
shape — round-trips correctly end to end with no special-casing needed,
because it rides the same `uri_to_path` helper every other capability
already depends on. No fixes were needed; none applied.
## Review
**2026-08-24 — lead.** Reviewed after QA's clean ship verdict; gates run
independently. The find of the round is the `initialize_finish` trap —
lsp-server consumes the `initialized` notification, so the
protocol-suggested registration point is provably dead code; QA verified
that against the vendored source rather than taking the claim on faith,
and the README records it where the next reader will look. Registration
payloads, per-notification coalescing, and the id discipline are all
boring in the right way. QA's percent-encoded-space end-to-end run (the
owner's actual "Clock Divider" path shape) is exactly the reality-check
this feature needed. The three honest gaps (no debounce — measured at
~0.3s per notification on the full corpus, nested `-f` unwatched,
static-watcher clients unchanged) are disclosed in both places a user
would look. Accepted; M9 checked off in the umbrella plan and TODO §8.
+2 -1
View File
@@ -155,7 +155,7 @@ built but nothing consumes yet. Ordered by value ÷ cost:
shows `.clk:`/`.rst_n:` ghost labels from the instantiated module's
definition (same index facts as M4); parameter names on ordered
`#(...)` overrides too. High everyday value in RTL review.
- [ ] **External file-change awareness** — the index rebuilds on save and
- [x] **External file-change awareness** — the index rebuilds on save and
didOpen only; a `git pull`, an external edit, or editing the `.f`
filelist itself goes unnoticed until the next save. Register
`workspace/didChangeWatchedFiles` (sources + the filelist) and reindex.
@@ -263,6 +263,7 @@ commit — in order:
- [x] Backlog triage after M6 — LSP-parity gap list added, 2026-08-24
- [x] M7 references-nav — done, QA clean first pass, reviewed
- [x] M8 inlay-hints — done, one QA HIGH fixed in-round, reviewed
- [x] M9 file-watching — done, QA clean first pass, reviewed
## Work log
+16 -1
View File
@@ -32,6 +32,7 @@ looks like language knowledge in here is a bug or a `Handshake` request.
| `textDocument/signatureHelp` | `vlog_refactor::instantiation_plan` | The instantiated module's ports (or, inside `#( ... )`, its parameters) with the active one highlighted — by name for a named list, by position for an ordered one. Triggers: `(` and `,`. Same feature README |
| `textDocument/inlayHint` | `vlog_refactor::instantiation_plan` | Ghost port names on an **ordered** connection list (`u1 (clk, rst_n)`) and parameter names on ordered `#( ... )` overrides, read from the instantiated module's declaration. Range-scoped; named lists, `.*`, omitted positions, connections past the last port, gate primitives and modules the index cannot resolve get nothing at all — a hint is decoration and never guesses. No `resolveProvider`. See `docs/features/inlay-hints/README.md` |
| `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` |
Deferred, deliberately, and named in Status/TODO below: ~~range formatting
(waits on TODO.md §2 `--lines`)~~ **delivered by range-formatting (round 18):
@@ -188,7 +189,7 @@ handler is milliseconds; the complexity of a worker pool buys nothing yet.
| layer | rebuilt when | cost |
|---|---|---|
| a document's `Semantics` + tokens + diagnostics | every `didOpen`/`didChange` | one file, full recompute |
| the `WorkspaceIndex` | `initialize`, and every `didSave` | full re-scan of the roots |
| the `WorkspaceIndex` | `initialize`, every `didSave`, every `workspace/didChangeWatchedFiles`, and a changed `vfmt.exclude`/`vfmt.filelist` | full re-scan of the roots |
**Per-file recompute on every keystroke** is the strategy TODO.md §6 states
("per-file recompute is fine at Verilog file sizes"); salsa is explicitly
@@ -209,6 +210,20 @@ point where the answer is expected to change anyway. Measured cost of a
rebuild: 0.68 s for the 860-file corpus (the workspace index's own baseline),
plus the file reads.
**Changes made outside the editor close on the next notification, not on the
next save** (M9, `docs/features/file-watching/README.md`). The server registers
`workspace/didChangeWatchedFiles` for `**/*.{v,vh,sv,svh}` and for the
configured filelist's own path, so a `git pull`, a checkout, a generated file
or an externally edited `.f` rebuilds the index straight away — one rebuild per
notification, however many files that notification names. **The window that
remains, honestly:** a client that did not advertise
`workspace.didChangeWatchedFiles.dynamicRegistration` cannot be registered
(the protocol has no static form of the capability) and keeps the save-only
model above; nested `-f` filelists are not watched, only the root one;
`vfmt.toml` is not watched either (it is re-read on every rebuild, so the next
rebuild from any cause picks it up); and there is no time-based debouncing, so
a burst arriving as several separate notifications costs one rebuild each.
**Definition targets in other files need that file's text** to turn a
`TextRange` into a `Range`, and the index deliberately keeps no file contents.
The server resolves a target by taking the **open buffer's text if that path